package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.f4b6a3.ulid.UlidCreator;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.base.LoginRequest;
import com.qingcloud.adminbackend.config.PasswordEncoder;
import com.qingcloud.adminbackend.config.RedisUtil;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.controller.open.param.ChangePwdParam;
import com.qingcloud.adminbackend.controller.open.param.GridUserParam;
import com.qingcloud.adminbackend.entity.config.SysCommonConfig;
import com.qingcloud.adminbackend.entity.domain.DomainTreeVO;
import com.qingcloud.adminbackend.entity.domain.SysDomain;
import com.qingcloud.adminbackend.entity.role.MiniRole;
import com.qingcloud.adminbackend.entity.role.SysRole;
import com.qingcloud.adminbackend.entity.stationgroup.*;
import com.qingcloud.adminbackend.entity.sysfunction.SysFunction;
import com.qingcloud.adminbackend.entity.sysfunction.SysRoleFunction;
import com.qingcloud.adminbackend.entity.sysfunction.SysUserFunction;
import com.qingcloud.adminbackend.entity.sysorder.SysBusinessApp;
import com.qingcloud.adminbackend.entity.sysorder.SysUserOrderMgr;
import com.qingcloud.adminbackend.entity.sysorder.SysUserOrderMgrDTO;
import com.qingcloud.adminbackend.entity.sysorg.*;
import com.qingcloud.adminbackend.entity.taskorg.SysUserTaskOrg;
import com.qingcloud.adminbackend.entity.user.*;
import com.qingcloud.adminbackend.entity.userdomain.UserDomainDTO;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroupDTO;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroupUser;
import com.qingcloud.adminbackend.entity.userrole.SysUserRole;
import com.qingcloud.adminbackend.entity.userrole.UserRoleVO;
import com.qingcloud.adminbackend.entity.userrole.UserRoles;
import com.qingcloud.adminbackend.enums.DataFunctionEnum;
import com.qingcloud.adminbackend.enums.UcRoleEnum;
import com.qingcloud.adminbackend.enums.UserRoleEnum;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.pojo.cloud.CloudApiRequest;
import com.qingcloud.adminbackend.service.ISysDomainService;
import com.qingcloud.adminbackend.service.ISysOrderService;
import com.qingcloud.adminbackend.service.ISysUserService;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.adminbackend.utils.JwtUtil;
import com.qingcloud.adminbackend.utils.PinYinUtil;
import com.qingcloud.adminbackend.utils.StringUtil;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.passwordencode.Md5PasswordEncoder;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import lombok.SneakyThrows;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author luozehua
 * @since 2018-11-19
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserOrgMapper sysUserOrgMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUsergroupUserMapper sysUsergroupUserMapper;

    @Resource
    private SysUserOrgMgrMapper sysUserOrgMgrMapper;

    @Resource
    private SysUserStationGroupMapper sysUserStationGroupMapper;

    @Resource
    private SysUserFunctionMapper sysUserFunctionMapper;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private SysUserOrderMgrMapper sysUserOrderMgrMapper;

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SysCommonConfigMapper commonConfigMapper;
    @Resource
    private SysOrderMapper sysOrderMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUsergroupMapper usergroupMapper;
    @Resource
    private SysStationGroupMapper sysStationGroupMapper;
    @Resource
    private SysOrgStationGroupMapper sysOrgStationGroupMapper;
    @Resource
    private SysUsergroupStationgroupMapper sysUsergroupStationgroupMapper;
    @Resource
    private SysFunctionMapper sysFunctionMapper;
    @Resource
    private SysUserStationgroupMgrstationMapper userStationgroupMgrstationMapper;
    @Resource
    private ISysOrderService sysOrderService;
    @Resource
    private SysRoleFunctionMapper roleFunctionMapper;
    @Resource
    private Md5PasswordEncoder md5PasswordEncoder;

    @Resource
    private SysDomainMapper sysDomainMapper;
    @Resource
    private SysUserTaskOrgMapper sysUserTaskOrgMapper;
    @Resource
    private ISysDomainService sysDomainService;
    @Resource
    private SysBusinessAppMapper businessAppMapper;

    @Value("${file.cos-url}")
    private String cosUrl;

    /**
     * 根据用户Id获取用户信息
     *
     * @param userId
     */
    @Override
    public SysUser getUserDetails(String userId) {
        // 根据用户Id获取用户信息
        SysUser user = sysUserMapper.getUserDetails(userId);
        if (user != null) {
            List<String> businessTypeIdsArr = new ArrayList<>();
            List<String> businessTypeNameArr = new ArrayList<>();
            List<String> roleArr = new ArrayList<>();
            List<String> roleIdArr = new ArrayList<>();
            List<String> orgArr = sysUserMapper.getUserOrg(userId);
            String orgBusinessType = sysUserMapper.getUserOrgBusinessType(userId);
            List<String> functionList = getDataFunction(userId);

            //设备管理权限
            List<SysStationGroupVO> stationGroup = getMgrstationStationgroup(userId);

            List<Map<String, Object>> role = getRoleBusinessTypeByAuthorUser(userId);
            for (Map map : role) {
                businessTypeIdsArr.add((String) map.get("value"));
                businessTypeNameArr.add((String) map.get("label"));

                List<Map<String, Object>> children = (List<Map<String, Object>>) map.get("children");
                for (Map childMap : children) {
                    roleIdArr.add((String) childMap.get("value"));
                    roleArr.add((String) childMap.get("label"));
                }

            }
            user.setDataFunction(functionList);
            user.setRoleNames(roleArr);
            user.setRoleIds(roleIdArr);
            user.setBusinessTypeIdsArr(businessTypeIdsArr);
            user.setBusinessTypeNameIdsArr(businessTypeNameArr);
            user.setOrgNames(orgArr);
            user.setRole(role);
            user.setOrgBusinessType(orgBusinessType);
            // 前端要求返回空数组不返回null
            user.setUserGroupIds(new ArrayList<>());
            user.setStationGroupIds(new ArrayList<>());
            user.setOrgMgrIds(new ArrayList<>());
            user.setStationGroup(stationGroup);
        }
        return user;
    }

    /**
     * 功能描述: 获取DataFunction
     *
     * @param: userId
     * @return:
     * @auther: Destiny
     * @date: 2021/1/8 上午9:52
     */
    private List<String> getDataFunction(String userId) {
        String dataFunctions = sysUserRoleMapper.findUserDataFunction(userId);
        if (StrUtil.isBlank(dataFunctions)) {
            return Collections.emptyList();
        }
        List<String> functionList = Arrays.asList(dataFunctions.split(","));
        //去重
        Set<String> set = new HashSet<>();
        for (String str : functionList) {
            set.add(str);
        }
        //排序
        set.stream().sorted(Comparator.reverseOrder());

        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        List<String> list3 = new ArrayList<>();

        for (String fun : set) {
            if (fun.contains("4") || fun.contains("5") || fun.contains("6")) {
                list1.add(fun);
            } else {
                list2.add(fun);
            }
        }

        if (list2.size() > 0) {
            list3.add(list2.get(0));
        }
        list3.addAll(list1);
        return list3;
    }

    /**
     * 功能描述: 获取用户业务类型和角色
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2021/1/7 上午10:26
     */
    public List<Map<String, Object>> getRoleBusinessTypeByAuthorUser(String userId) {
        //所有业务类型

        List<SysBusinessTypeDTO> data = sysOrderMapper.getBusinessTypeByUserId(null, true, true);
        Map<String, SysBusinessTypeDTO> businessTypeMap = data.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));

        List<UserRoleBo> roleBoList = sysUserRoleMapper.findRoleInfoByUserId(userId);

        for (UserRoleBo roleBo : roleBoList) {
            SysBusinessTypeDTO typeDTO = businessTypeMap.get(roleBo.getBusinessType());
            roleBo.setBusinessName(typeDTO.getName());
        }

        Map<String, List<UserRoleBo>> groups = roleBoList.stream().collect(Collectors.groupingBy(s -> s.getBusinessType()));

        List<Map<String, Object>> dataList = new ArrayList<>();
        for (Map.Entry<String, List<UserRoleBo>> entry : groups.entrySet()) {
            String key = entry.getKey();

            SysBusinessTypeDTO typeDTO = businessTypeMap.get(key);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("value", key);
            dataMap.put("label", typeDTO.getName());

            List<UserRoleBo> value = entry.getValue();

            List<Map<String, Object>> roleDataList = new ArrayList<>();
            for (UserRoleBo userRoleBo : value) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("value", userRoleBo.getRoleId());
                roleMap.put("label", userRoleBo.getRoleName());
                roleDataList.add(roleMap);
                dataMap.put("children", roleDataList);
            }
            dataList.add(dataMap);
        }

        return dataList;
    }

    public String defaultUserName() {
        //随机登录名
        String s = StringUtil.generateString(10);
        //检测是数据库中是否存在
        Boolean aBoolean = userNameExist(s);
        if (aBoolean) {
            return defaultUserName();
        } else {
            return s;
        }
    }


    /**
     * 新增用户
     *
     * @param userParam
     * @param createId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addAirUser(AddAirUserBO userParam, String createId) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userParam, user);
        String userName = user.getUserName();
        if (!StringUtils.isEmpty(userName)) {
            user.setIsDefault(0);
        } else {
            user.setUserName(defaultUserName());
            user.setIsDefault(1);
        }
        String userId = UUID.randomUUID().toString().replaceAll("-", "");
        //空气用户
        user.setUserType(1);
        user.setFullNamePinyin(PinYinUtil.cn2Spell(user.getFullName()));
        int save = insertUser(user, createId, userId);
        if (save > 0) {
            //step 01
            //用户所属客户
            List<String> orgIds = user.getOrgIds();
            orgIds.forEach(orgId -> {
                SysUserOrg userOrg = new SysUserOrg();
                userOrg.setOrgId(orgId);
                userOrg.setUserId(userId);
                userOrg.setCreateBy(createId);
                userOrg.setCreateDt(new Date());
                userOrg.setModifyBy(createId);
                userOrg.setModifyDt(new Date());
                sysUserOrgMapper.insert(userOrg);
            });
            //插入用户和用户身份
            List<String> roleIds = user.getRoleIds();
            insertUerRole(roleIds, createId, userId);
            //step 02
            //插入用户，用户组关系
            List<String> userGroupIds = user.getUserGroupIds();
            airStep02(userGroupIds, createId, userId);
            //step 03
            List<String> orgMgrIds = user.getOrgMgrIds();
            List<String> stationGroupIds = user.getStationGroupIds();
            List<String> functionIds = user.getFunctionIds();
            airStep03(orgMgrIds, stationGroupIds, functionIds, createId, userId, roleIds);
        }

        if (save > 0) {
            return userId;
        }
        return "";
    }

    /**
     * 新增蛙鸣用户
     *
     * @param userParam
     * @param createId
     */
    @Deprecated
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addWmUser(AddWmUserBO userParam,
                             Map<String, Collection<String>> userAuthFunctions,
                             List<String> orgTreeByLoginUser,
                             Set<String> orders,
                             Set<String> oamOrders,
                             String createId) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userParam, user);
        String userName = user.getUserName();
        if (!StringUtils.isEmpty(userName)) {
            user.setIsDefault(0);
        } else {
            user.setUserName(defaultUserName());
            user.setIsDefault(1);
        }
        String userId = UUID.randomUUID().toString().replaceAll("-", "");
        //蛙鸣用户
        user.setUserType(2);
        user.setFullNamePinyin(PinYinUtil.cn2Spell(user.getFullName()));
        Integer save = insertUser(user, createId, userId);
        if (save > 0) {
            //用户角色
            List<RoleBusinessBO> roleIds = userParam.getRoleBusiness();
            insertWmUserRole(createId, userId, roleIds);
            //用户授权
            userParam.setId(userId);
            List<String> stationGroupIds = new ArrayList<>();
            reWmAuth(userParam, userAuthFunctions, orgTreeByLoginUser, orders, oamOrders, createId, stationGroupIds);
        }
        return save;
    }

    private void insertWmUserRole(String createId, String userId, List<RoleBusinessBO> roleIds) {
        roleIds.forEach(role -> {
            String roleId = role.getRoleId();
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(Integer.valueOf(roleId));
            //业务
            userRole.setCreateBy(createId);
            userRole.setModifyBy(createId);
            userRole.setCreateDt(new Date());
            userRole.setModifyDt(new Date());
            sysUserRoleMapper.insert(userRole);
        });
    }


    /**
     * 插入用户
     *
     * @return
     */
    private Integer insertUser(SysUser user, String createId, String userId) {
        user.setId(userId);
        user.setCreateBy(createId);
        user.setCreateDt(new Date());
        user.setModifyBy(createId);
        user.setModifyDt(new Date());
        user.setDeleteFlag("0");
        user.setStatus("0");
        QueryWrapper<SysCommonConfig> query = new QueryWrapper<>();
        query.eq("`key`", "user_default_pwd");
        SysCommonConfig sysCommonConfig = commonConfigMapper.selectOne(query);
        String defaultPwd = StringUtils.isEmpty(sysCommonConfig.getValue()) ? WamingConstant.DEFAULT_PWD : sysCommonConfig.getValue();
        user.setUserPassword(passwordEncoder.md5PasswordEncoder().encodePassword(defaultPwd, user.getId()));
        user.setLoginCount(0);
        return sysUserMapper.insert(user);
    }

    /**
     * 插入用户角色
     *
     * @param createId
     * @param userId
     * @return
     */
    private void insertUerRole(List<String> roleIds, String createId, String userId) {
        roleIds.forEach(id -> {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setCreateBy(createId);
            userRole.setRoleId(Integer.valueOf(id));
            userRole.setModifyBy(createId);
            userRole.setCreateDt(new Date());
            userRole.setModifyDt(new Date());
            sysUserRoleMapper.insert(userRole);
        });
    }

    /**
     * 添加空气用户第三个，授权
     *
     * @param createId
     * @param userId
     */
    private void airStep03(List<String> orgMgrIds, List<String> stationGroupIds,
                           List<String> functionIds, String createId, String userId, List<String> roleIds) {
        //客户授权
        String roleId = roleIds.get(0);
        if (!CollectionUtils.isEmpty(orgMgrIds)) {
            orgMgrIds.forEach(orgMgrId -> {
                SysUserOrgMgr userOrgMgr = new SysUserOrgMgr();
                userOrgMgr.setUserId(userId);
                userOrgMgr.setOrgId(orgMgrId);
                userOrgMgr.setManage(1);
                userOrgMgr.setRead(1);
                userOrgMgr.setRoleId(Integer.valueOf(roleId));
                userOrgMgr.setCreateBy(createId);
                userOrgMgr.setModifyBy(createId);
                userOrgMgr.setCreateDt(new Date());
                userOrgMgr.setModifyDt(new Date());
                sysUserOrgMgrMapper.insert(userOrgMgr);
            });
        }
        //设备组授权
        if (!CollectionUtils.isEmpty(stationGroupIds)) {
            // if (WamingConstant.COMPANY_EQUIPMENT_MANAGER_ID.equals(roleId)) {
            //企业用户
            stationGroupIds.forEach(stationGroupId -> {
                SysUserStationgroupMgrstation userStationgroupMgrstation = new SysUserStationgroupMgrstation();
                userStationgroupMgrstation.setUserId(userId);
                userStationgroupMgrstation.setGroupId(stationGroupId);
                userStationgroupMgrstation.setRoleId(roleId);
                userStationgroupMgrstation.setCreateBy(createId);
                userStationgroupMgrstation.setModifyBy(createId);
                userStationgroupMgrstation.setCreateDt(new Date());
                userStationgroupMgrstation.setModifyDt(new Date());
                userStationgroupMgrstationMapper.insert(userStationgroupMgrstation);
            });
            //  }
        }


        //功能授权
        if (!CollectionUtils.isEmpty(functionIds)) {
            functionAuth(createId, functionIds, userId, roleId);
        }
    }

    /**
     * 添加空气用户第二步，添加设备组关系
     *
     * @param createId
     * @param userId
     */
    private void airStep02(List<String> userGroupIds, String createId, String userId) {
        userGroupIds.forEach(ug -> {
            SysUsergroupUser userGroupUser = new SysUsergroupUser();
            userGroupUser.setGroupId(ug);
            userGroupUser.setUserId(userId);
            userGroupUser.setCreateBy(createId);
            userGroupUser.setModifyBy(createId);
            userGroupUser.setCreateDt(new Date());
            userGroupUser.setModifyDt(new Date());
            sysUsergroupUserMapper.insert(userGroupUser);
        });
    }

    /**
     * 更新健康空气用户
     *
     * @param airUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateAirUser(AddAirUserBO airUser, List<String> mgrList,
                                 List<String> mgrStationGroup,
                                 List<String> userAuthFunctions, String userId, Boolean isAdmin) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(airUser, user);
        SysUser sysUser = this.baseMapper.selectById(airUser.getId());
        user.setIsDefault(sysUser.getIsDefault());
        int isDefault = sysUser.getIsDefault();
        String userName = sysUser.getUserName();
        String updateUserName = airUser.getUserName();
        if (isDefault == 1) {
            //随机用户名
            if (!updateUserName.equals(userName)) {
                //修改
                user.setIsDefault(0);
            } else {
                user.setIsDefault(1);
            }
        }
        user.setUserType(1);
        //修改角色
        List<String> roleIds = user.getRoleIds();
        if (!CollectionUtils.isEmpty(roleIds)) {
            //判断是否修改了身份
            List<UserRoleVO> userRole = sysUserRoleMapper.findRoleByUserId(user.getId());
            List<String> oriRoleIds = new ArrayList<>();
            userRole.forEach(e -> oriRoleIds.add(e.getId().toString()));
            if (!CommonUtil.isSameList(oriRoleIds, roleIds)) {
                //修改了身份
                //删除所有的用户
                QueryWrapper<SysUserRole> query = new QueryWrapper<>();
                query.eq("user_id", user.getId());
                sysUserRoleMapper.delete(query);
                roleIds.forEach(role -> {
                    String roleId = role;
                    //重新插入
                    SysUserRole param = new SysUserRole();
                    param.setUserId(user.getId());
                    param.setRoleId(Integer.valueOf(roleId));
                    sysUserRoleMapper.insert(param);
                });

            }
        }
        user.setFullNamePinyin(PinYinUtil.cn2Spell(user.getFullName()));
        return sysUserMapper.updateAirUser(user);
    }

    /**
     * 更新蛙鸣用户
     *
     * @param wmUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateWmUser(AddWmUserBO wmUser, Set<String> orders,
                                List<String> orgTreeByLoginUser,
                                Set<String> oamOrders) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(wmUser, user);
        String userId = wmUser.getId();
        SysUser sysUser = this.baseMapper.selectById(userId);
        user.setIsDefault(sysUser.getIsDefault());
        int isDefault = sysUser.getIsDefault();
        String userName = sysUser.getUserName();
        String updateUserName = wmUser.getUserName();
        if (isDefault == 1) {
            //随机用户名
            if (!updateUserName.equals(userName)) {
                //修改
                user.setIsDefault(0);
            } else {
                user.setIsDefault(1);
            }
        }
        user.setUserType(2);
        List<RoleBusinessBO> roleIds = wmUser.getRoleBusiness();
        if (!CollectionUtils.isEmpty(roleIds)) {
            //判断是否修改了身份
            List<UserRoleVO> userRole = sysUserRoleMapper.findRoleByUserId(userId);
            List<String> oriRoleIds = new ArrayList<>();
            userRole.forEach(e -> oriRoleIds.add(e.getId().toString()));
            //复制集合
            List<String> oriRoleIdsTemp = new ArrayList<>();
            oriRoleIds.forEach(e -> oriRoleIdsTemp.add(e));

            List<String> newRoleIds = new ArrayList<>();
            roleIds.forEach(e -> newRoleIds.add(e.getRoleId()));
            //判断两个集合是否相等
            if (!CommonUtil.isSameList(oriRoleIds, newRoleIds)) {
                //修改了用户身份
                //删除所有的用户
                QueryWrapper<SysUserRole> query = new QueryWrapper<>();
                query.eq("user_id", userId);
                sysUserRoleMapper.delete(query);
                roleIds.forEach(role -> {
                    String roleId = role.getRoleId();
                    String healthFlag = role.getHealthFlag();
                    String weatherFlag = role.getWeatherFlag();
                    //重新插入
                    SysUserRole param = new SysUserRole();
                    param.setUserId(userId);
                    param.setRoleId(Integer.valueOf(roleId));
                    sysUserRoleMapper.insert(param);
                });
                //删除用户身份权限
                //交集
                oriRoleIds.retainAll(newRoleIds);
                //差集
                oriRoleIdsTemp.removeAll(oriRoleIds);
                //删除权限关系(oriRoleIdsTemp--已经被删除的身份)
                //权限全部删除
                deleteWmUserAuth(userId, oriRoleIdsTemp, orders, orgTreeByLoginUser, oamOrders);
            }
        }
        user.setFullNamePinyin(PinYinUtil.cn2Spell(user.getFullName()));
        return sysUserMapper.updateAirUser(user);
    }

    @Override
    public IPage<AirUserVO> findPageAirUser(AirUserBo sysUser, String userId, Boolean isAdmin) {
        Page<AirUserBo> page = new Page<>(sysUser.getCurrentPage(), sysUser.getPerPage());
        SysUser sysUser2 = sysUserMapper.selectById(userId);
        Integer adminFlag = sysUser2.getAdminFlag();
        List<String> userIds = new ArrayList<>();
        //登录用户可管理的客户
        List<SysOrg> orgs = getUserMgrOrg(isAdmin, userId, adminFlag);
        if (!CollectionUtils.isEmpty(orgs)) {
            List<String> orgIds = new ArrayList<>();
            orgs.forEach(org -> orgIds.add(org.getId()));
            QueryWrapper<SysUserOrg> query = new QueryWrapper<>();
            query.in("org_id", orgIds);
            List<SysUserOrg> sysUserOrgs = sysUserOrgMapper.selectList(query);
            sysUserOrgs.forEach(e -> userIds.add(e.getUserId()));

            //分页查询
            IPage<AirUserVO> pageAirUser = sysUserMapper.findPageAirUser(page, sysUser,
                    userIds, isAdmin ? "yes" : "no",
                    adminFlag == 1 ? "yes" : "no");
            //组装数据
            List<AirUserVO> records = pageAirUser.getRecords();
            if (isAdmin || adminFlag == 1) {
                records.forEach(e -> e.setOrgAuth(1));
            } else {
                //有写权限的id
                List<String> manageOrgIds = new ArrayList<>();
                orgs.forEach(k -> {
                    if (k.getManage() == 1) {
                        manageOrgIds.add(k.getId());
                    }
                });
                records.forEach(e -> {
                    String orgId = e.getOrgId();
                    if (manageOrgIds.contains(orgId)) {
                        e.setOrgAuth(1);
                    } else {
                        e.setOrgAuth(0);
                    }
                });
            }
            return pageAirUser;
        } else {
            //没有客户或者没有用户ID
            return new Page<>();
        }
    }

    /**
     * 根据用户名称查询用户
     *
     * @param userName
     * @return
     */
    @Override
    public SysUser findByUserNameOrPhone(String userName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.or(q -> q.eq("user_name", userName).or().eq("mobileno", userName))
                .and(q -> q.eq("delete_flag", 0)).and(q -> q.le("status", 2));
        return sysUserMapper.selectOne(queryWrapper);
    }

    /**
     * 重置密码
     *
     * @param userBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer resetPwd(UserBO userBO) {
        if (StringUtils.isEmpty(userBO.getNewPwd()) || StringUtils.isEmpty(userBO.getNewPwd_01())) {
            return -1;
        } else if (!StringUtils.isEmpty(userBO.getNewPwd()) && !userBO.getNewPwd().equals(userBO.getNewPwd_01())) {
            return -2;
        } else {
            //重置密码
            this.baseMapper.updatePasswordById(userBO.getUserId(),
                    passwordEncoder.md5PasswordEncoder().encodePassword(userBO.getNewPwd(), userBO.getUserId()));
        }
        return 1;
    }


    private List<SysOrg> getUserMgrOrg(Boolean isAdmin, String userId, Integer adminFlag) {
        List<SysOrg> allManageOrgByUser = new ArrayList<>();
        if (isAdmin || adminFlag == 1) {
            //查询全部
            QueryWrapper<SysOrg> query = new QueryWrapper<>();
            query.eq("delete_flag", "0");
            allManageOrgByUser = sysOrgMapper.selectList(query);
            allManageOrgByUser.forEach(e -> e.setManage(1));
        } else {
            List<SysOrg> temp = sysUserOrgMgrMapper.findAllManageOrgByUser(userId, null);
            //判断是否是一级客户
            for (SysOrg org : temp) {
                int category = org.getCategory();
                if (category == 1) {
                    //查询下面的分支结构
                    String id = org.getId();
                    List<SysOrg> subOrgs = sysOrgMapper.selectByMap(ImmutableMap.of("parent_id", id));
                    if (org.getManage() == 1) {
                        subOrgs.forEach(e -> e.setManage(1));
                    }
                    allManageOrgByUser.add(org);
                    allManageOrgByUser.addAll(subOrgs);
                } else {
                    //分支机构
                    allManageOrgByUser.add(org);
                }
            }
        }
        return allManageOrgByUser;
    }

    /**
     * 根据用户Ids删除用户
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteUserByIds(List<String> ids, String userType, Boolean isAdmin, String loginUserId) {
        if (isAdmin) {
            // 删除健康空气用户
            ids.forEach(userId -> deleteUser(userId));
            return new AjaxResult(WamingConstant.SUCCESS, "删除成功", "删除成功");
        }
        // 健康空气用户
        if (userType.equals("1")) {
            Boolean isOrgAdmin = true;
            //判断登录用户的身份，如果是客服，客服可以删除写权限客户下的所有用户，包含在客户管理增加客户时绑定的企业管理员
            List<SysUserRole> userRoles = sysUserRoleMapper.selectByMap(ImmutableMap.of("user_id", loginUserId));
            if (CollectionUtils.isEmpty(userRoles)) {
                return new AjaxResult(WamingConstant.FAILURE, "无权删除", "删除失败");
            } else {
                SysUserRole userRole = userRoles.get(0);
                //客服
                //查询登录用户有写权限的客户
                List<String> loginUserOrgMgrIds = new ArrayList<>();
                List<SysOrg> sysUserOrgMgrs = sysUserOrgMgrMapper.findAllOrgAndChildByUser(loginUserId, null)
                        .stream().filter(it -> WamingConstant.ONE.equals(it.getManage())).collect(Collectors.toList());
                sysUserOrgMgrs.forEach(e -> loginUserOrgMgrIds.add(e.getId()));
                //查询被删用户对应的客户
                List<String> deleteUserOrgIds = new ArrayList<>();
                QueryWrapper<SysUserOrg> query = new QueryWrapper<>();
                query.in("user_id", ids);
                List<SysUserOrg> userOrg = sysUserOrgMapper.selectList(query);
                userOrg.forEach(e -> deleteUserOrgIds.add(e.getOrgId()));
                isOrgAdmin = loginUserOrgMgrIds.containsAll(deleteUserOrgIds);
                if (!UserRoleEnum.SERVICER_ID.code.equals(userRole.getRoleId())) {
                    // 判断ids中是否包含企业最高管理员
                    for (String userId : ids) {
                        SysUser user = sysUserMapper.selectById(userId);
                        // 如果是企业内部最高管理员
                        if (user.getOrgAdmin() == 1) {
                            isOrgAdmin = false;
                        }
                    }
                }
                // 如果ids中包含企业内部最高管理员
                if (!isOrgAdmin) {
                    return new AjaxResult(WamingConstant.FAILURE, "无权删除", "删除失败");
                } else {
                    // 删除健康空气用户
                    ids.forEach(userId -> {
                        deleteUser(userId);
                    });
                }
            }
        } else {
            // 删除蛙鸣用户
            ids.forEach(userId -> {
                deleteUser(userId);
            });
        }
        return new AjaxResult(WamingConstant.SUCCESS, "删除成功", "删除成功");
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    private void deleteUser(String userId) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setDeleteFlag("1");
        sysUserMapper.updateById(user);
        // 删除用户组关系
        QueryWrapper<SysUsergroupUser> userGroupUser = new QueryWrapper<>();
        userGroupUser.eq("user_id", userId);
        sysUsergroupUserMapper.delete(userGroupUser);
        // 删除用户关联设备
        QueryWrapper<SysUserStationGroup> userGroupStationGroup = new QueryWrapper<>();
        userGroupStationGroup.eq("user_id", userId);
        sysUserStationGroupMapper.delete(userGroupStationGroup);
        // 删除用户客户关系
        QueryWrapper<SysUserOrg> userOrg = new QueryWrapper<>();
        userOrg.eq("user_id", userId);
        sysUserOrgMapper.delete(userOrg);
        // 删除可管理户客户关系
        QueryWrapper<SysUserOrgMgr> userOrgMgr = new QueryWrapper<>();
        userOrgMgr.eq("user_id", userId);
        sysUserOrgMgrMapper.delete(userOrgMgr);
        // 删除用户身份关系
        QueryWrapper<SysUserRole> userRole = new QueryWrapper<>();
        userRole.eq("user_id", userId);
        sysUserRoleMapper.delete(userRole);
        // 删除用户关联功能
        QueryWrapper<SysUserFunction> userFunction = new QueryWrapper<>();
        userFunction.eq("user_id", userId);
        sysUserFunctionMapper.delete(userFunction);
        // 删除用户管理订单关系
        QueryWrapper<SysUserOrderMgr> userOrderMgr = new QueryWrapper<>();
        userOrderMgr.eq("user_id", userId);
        sysUserOrderMgrMapper.delete(userOrderMgr);
        //设备组
        QueryWrapper<SysUserStationgroupMgrstation> userStationgroupMgrstation = new QueryWrapper<>();
        userStationgroupMgrstation.eq("user_id", userId);
        userStationgroupMgrstationMapper.delete(userStationgroupMgrstation);
    }


    /**
     * 运维订单授权
     *
     * @param createId
     * @param userId
     * @param oamAuth
     */
    private void oamAuth(String createId, String userId, WmAuthParamBO oamAuth, Set<String> oamOrders) {
        if (oamAuth != null) {
            List<WmAuthTempBO> auths = oamAuth.getAuths();
            if (CollectionUtils.isEmpty(oamOrders)) {
                return;
            }
            auths.forEach(oam -> {
                SysUserOrderMgr userOrderMgr = new SysUserOrderMgr();
                userOrderMgr.setUserId(userId);
                userOrderMgr.setOrderId(oam.getAuthId());
                userOrderMgr.setManage(oam.getManage());
                userOrderMgr.setRead(oam.getRead());
                userOrderMgr.setCreateBy(createId);
                userOrderMgr.setCreateDt(new Date());
                userOrderMgr.setModifyBy(createId);
                userOrderMgr.setModifyDt(new Date());
                sysUserOrderMgrMapper.insert(userOrderMgr);
            });
        }

    }

    /**
     * 客户授权
     *
     * @param createId
     * @param userId
     * @param csAuth
     */
    private void orgAuth(String createId, String userId, WmAuthParamBO csAuth, List<String> orgTreeByLoginUser) {
        if (csAuth != null) {
            List<WmAuthTempBO> auths = csAuth.getAuths();
            if (CollectionUtils.isEmpty(orgTreeByLoginUser)) {
                return;
            }
            auths.forEach(cs -> {
                SysUserOrgMgr orgMgr = new SysUserOrgMgr();
                orgMgr.setUserId(userId);
                orgMgr.setOrgId(cs.getAuthId());
                orgMgr.setManage(cs.getManage());
                orgMgr.setRead(cs.getRead());
                orgMgr.setCreateBy(createId);
                orgMgr.setCreateDt(new Date());
                orgMgr.setModifyBy(createId);
                orgMgr.setModifyDt(new Date());
                sysUserOrgMgrMapper.insert(orgMgr);
            });
        }

    }

    private void functionAuth(String createId, List<String> sellFunctions, String userId, String roleId) {
        List<SysUserFunction> userFunctionList = sellFunctions.stream().map(funId -> {
            SysUserFunction userFunction = new SysUserFunction();
            userFunction.setUserId(userId);
            userFunction.setRoleId(roleId);
            userFunction.setFunctionId(funId);
            userFunction.setCreateBy(createId);
            userFunction.setModifyBy(createId);
            userFunction.setCreateDt(new Date());
            userFunction.setModifyDt(new Date());
            return userFunction;
        }).collect(Collectors.toList());
        sysUserFunctionMapper.batchInsert(userFunctionList);
    }

    @Override
    public JSONObject getWmUserAuth(WmAuth wmAuth, String loginUserId, Boolean isAdmin) {
        //是否超级管理员
        if (!isAdmin) {
            SysUser sysUser = sysUserMapper.selectById(loginUserId);
            //是否是完全管理权限
            if (WamingConstant.ONE.equals(sysUser.getAdminFlag())) {
                isAdmin = true;
            }
        }
        String userId = wmAuth.getUserId();
        JSONObject result = new JSONObject();
        //获取用户的角色
        List<UserRoleVO> roles = sysUserRoleMapper.findRoleByUserId(userId);
        //获取最高权限
        Set<String> dataFunctionSet = roles.stream().map(it -> it.getDataFunction().split(","))
                .flatMap(Arrays::stream).collect(Collectors.toSet());
        //获取权限
        SysUserOrderMgrDTO sysUserOrderMgrDTO = new SysUserOrderMgrDTO();
        sysUserOrderMgrDTO.setUserId(userId);
        boolean finalIsAdmin = isAdmin;
        List<Object> authList = new ArrayList<>();
        if (dataFunctionSet.contains("1")) {
            //销售
            //获取客服权限
            List<SysOrgBO> orgAuth = sysUserOrgMgrMapper.findOrgMgrByUserId(userId, null);
            //如果没有管理权限，判断当前登录用户是否有他们的客户对应的管理权限或读取权限
            if (!finalIsAdmin) {
                List<SysOrgBO> loginUserAuth = sysUserOrgMgrMapper.findOrgMgrByUserId(loginUserId, null);

                //当前登录用户管理的客户ID
                List<String> loginUserManage = loginUserAuth.stream()
                        .filter(it -> it.getManage() == 1).map(SysOrgBO::getId).collect(Collectors.toList());
                //当前登录用户读权限的客户ID
                List<String> loginUserRead = loginUserAuth.stream()
                        .filter(it -> it.getManage() == 1 || it.getRead() == 1).map(SysOrgBO::getId).collect(Collectors.toList());
                orgAuth = orgAuth.stream().filter(it -> loginUserRead.contains(it.getId())).peek(it -> {
                    //当前登录用户只有读权限，不能勾选管理权限
                    if (!loginUserManage.contains(it.getId())) {
                        it.setEnableManage(0);
                    }
                    //如果有管理权限
                    if (it.getManage() == 1) {
                        //当前登录用户只有读权限
                        if (!loginUserManage.contains(it.getId())) {
                            it.setManage(2);
                        }
                    }
                }).collect(Collectors.toList());
            }
            authList.addAll(orgAuth);
        } else {
            //运维
            List<SysUserOrderMgrDTO> auth = sysOrderMapper.grantedOrders(sysUserOrderMgrDTO);
            if (!finalIsAdmin) {
                //如果不是admin，判断当前登录用户的读写权限
                //当前登录用户所有数据质控订单
                SysUserOrderMgrDTO tempDto = new SysUserOrderMgrDTO();
                tempDto.setUserId(loginUserId);
                Set<SysUserOrderMgrDTO> loginDataAuth = sysOrderService.getOrders(tempDto, false);
                //当前登录用户管理的订单ID
                List<String> loginUserManage = loginDataAuth.stream()
                        .filter(it -> it.getManage() == 1).map(SysUserOrderMgrDTO::getId).collect(Collectors.toList());
                //当前登录用户读权限的订单ID
                List<String> loginUserRead = loginDataAuth.stream()
                        .filter(it -> it.getManage() == 1 || it.getRead() == 1).map(SysUserOrderMgrDTO::getId).collect(Collectors.toList());
                auth = auth.stream().filter(it -> loginUserRead.contains(it.getId())).peek(it -> {
                    //当前登录用户只有读权限，不能勾选管理权限
                    if (!loginUserManage.contains(it.getId())) {
                        it.setEnableManage(0);
                    }
                    //如果有管理权限
                    if (it.getManage() == 1) {
                        //当前登录用户只有读权限
                        if (!loginUserManage.contains(it.getId())) {
                            it.setManage(2);
                        }
                    }
                }).collect(Collectors.toList());
            }
            authList.addAll(auth);
        }
        result.put("roles", roles);
        result.put("auths", authList);
        //功能
        QueryWrapper<SysUserFunction> userFunctionQueryWrapper = new QueryWrapper<>();
        userFunctionQueryWrapper.eq("user_id", userId);
        List<SysUserFunction> sysUserFunctions = sysUserFunctionMapper.selectList(userFunctionQueryWrapper);
        List<String> funs = sysUserFunctions.stream().map(SysUserFunction::getFunctionId).collect(Collectors.toList());
        //去掉的身份的功能
        List<String> roleIds = wmAuth.getRoleIds();
        if (CollUtil.isNotEmpty(roleIds)) {
            List<String> oriRoleIds = roles.stream().map(UserRoleVO::getId).map(String::valueOf).collect(Collectors.toList());
            oriRoleIds.removeAll(roleIds);
            if (CollUtil.isNotEmpty(oriRoleIds)) {
                QueryWrapper<SysRoleFunction> query = new QueryWrapper<>();
                query.in("role_id", oriRoleIds);
                List<SysRoleFunction> sysRoleFunctions = roleFunctionMapper.selectList(query);
                List<String> tempFun = sysRoleFunctions.stream().map(SysRoleFunction::getFunctionId).collect(Collectors.toList());
                funs.removeAll(tempFun);
            }
        }
        result.put("functions", funs);
        //是否是完全管理员
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser != null) {
            result.put("adminFlag", sysUser.getAdminFlag());
            //爬虫站
            result.put("crawlerFlag", sysUser.getCrawlerFlag());
            //设备池
            result.put("stationFlag", sysUser.getStationFlag());
        } else {
            result.put("adminFlag", 0);
            //爬虫站
            result.put("crawlerFlag", 0);
            //设备池
            result.put("stationFlag", 0);
        }
        return result;
    }

    /**
     * 删除指定用户的授权关系
     *
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWmUserAuth(String userId, List<String> roleIds,
                                 Set<String> orders,
                                 List<String> orgTreeByLoginUser,
                                 Set<String> oamOrders) {
        roleIds.forEach(roleId -> {
            //删除角色关系
            QueryWrapper<SysUserRole> userrole = new QueryWrapper<>();
            userrole.eq("user_id", userId);
            userrole.eq("role_id", roleId);
            sysUserRoleMapper.delete(userrole);
            //登录用户能使用的客户读写权限
            if (!CollectionUtils.isEmpty(orgTreeByLoginUser)) {
                //删除客服关系
                QueryWrapper<SysUserOrgMgr> userOrgMgr = new QueryWrapper<>();
                userOrgMgr.eq("user_id", userId);
                userOrgMgr.eq("role_id", roleId);
                userOrgMgr.in("org_id", orgTreeByLoginUser);
                sysUserOrgMgrMapper.delete(userOrgMgr);
            }

            if (!CollectionUtils.isEmpty(oamOrders)) {
                //删除运维关系
                QueryWrapper<SysUserOrderMgr> userOrderMgr = new QueryWrapper<>();
                userOrderMgr.eq("user_id", userId);
                userOrderMgr.eq("role_id", roleId);
                userOrderMgr.in("order_id", oamOrders);
                sysUserOrderMgrMapper.delete(userOrderMgr);
            }
        });

    }

    /**
     * 重新授权
     *
     * @param userParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reWmAuth(AddWmUserBO userParam,
                         Map<String, Collection<String>> userAuthFunctions,
                         List<String> orgTreeByLoginUser,
                         Set<String> orders,
                         Set<String> oamOrders,
                         String createId,
                         List<String> stationGroupIds) {
        String userId = userParam.getId();
        //修改角色业务关系
//        List<RoleBusinessBO> roleBusiness = userParam.getRoleBusiness();
        //修改角色
//        roleBusiness.forEach(role -> {
//            QueryWrapper<SysUserRole> query = new QueryWrapper<>();
//            query.eq("user_id", userParam.getId());
//            query.eq("role_id", role.getRoleId());
//            SysUserRole param = new SysUserRole();
//            param.setHealthFlag(role.getHealthFlag());
//            param.setWeatherFlag(role.getWeatherFlag());
//            sysUserRoleMapper.update(param, query);
//        });
        //删除用户功能
        QueryWrapper<SysUserFunction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        sysUserFunctionMapper.delete(queryWrapper);

        //删除以前的授权
        QueryWrapper<SysUserOrgMgr> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        sysUserOrgMgrMapper.delete(query);

        QueryWrapper<SysUserOrderMgr> query2 = new QueryWrapper<>();
        query2.eq("user_id", userId);
        sysUserOrderMgrMapper.delete(query2);

        //企业设备管理员，授权设备管理权限
        if (!CollectionUtils.isEmpty(stationGroupIds)) {
            //之前是企业设备管理员
            QueryWrapper<SysUserStationgroupMgrstation> station2 = new QueryWrapper<>();
            station2.eq("user_id", userId);
            station2.in("group_id", stationGroupIds);
            userStationgroupMgrstationMapper.delete(station2);
        }

        WmAuthParamBO auth = userParam.getAuth();
        Integer code = auth.getCode();

        if (DataFunctionEnum.ORG.code == code) {
            //按客户授权
            orgAuth(createId, userId, auth, orgTreeByLoginUser);
        } else if (DataFunctionEnum.ORDER.code == code || DataFunctionEnum.ORDER_READ.code == code) {
            //订单授权
            oamAuth(createId, userId, auth, orders);
        }
        //功能授权
        List<String> userFunctionIds = userParam.getUserFunctionIds();
        functionAuth(createId, userFunctionIds, userId, null);

        //设备组授权
        if (!CollectionUtils.isEmpty(userParam.getStationGroupIds())) {
            userParam.getStationGroupIds().forEach(stationGroupId -> {
                SysUserStationgroupMgrstation userStationgroupMgrstation = new SysUserStationgroupMgrstation();
                userStationgroupMgrstation.setUserId(userId);
                userStationgroupMgrstation.setGroupId(stationGroupId);
//                userStationgroupMgrstation.setRoleId(roleId);
                userStationgroupMgrstation.setCreateBy(createId);
                userStationgroupMgrstation.setModifyBy(createId);
                userStationgroupMgrstation.setCreateDt(new Date());
                userStationgroupMgrstation.setModifyDt(new Date());
                userStationgroupMgrstationMapper.insert(userStationgroupMgrstation);
            });
        }

        //其他权限
        if (!StringUtils.isEmpty(userParam.getAdminFlag())) {
            //修改是否是完全管理员权限
            SysUser user = new SysUser();
            user.setId(userId);
            user.setAdminFlag(userParam.getAdminFlag());
            sysUserMapper.updateById(user);
        }
        Integer crawlerFlag = userParam.getCrawlerFlag();
        Integer stationFlag = userParam.getStationFlag();
        sysUserMapper.updateCrawlerAuthAndPoolAuth(userId, crawlerFlag, stationFlag);
    }

    /**
     * 空气用户授权
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void airUserAuth(AirAuthBO userParam, List<String> mgrList,
                            List<String> mgrStationGroup,
                            List<String> userAuthFunctions,
                            String createId, Boolean isAdmin) {
        String userId = userParam.getId();
        //删除以前授权
        List<String> roleIds = userParam.getRoleIds();
        String roleId = "-1";
        if (!CollectionUtils.isEmpty(roleIds)) {
            roleId = roleIds.get(0);
        }
        deleteAirAuthByUserId(userId, roleId, mgrList, mgrStationGroup, userAuthFunctions);
        //重新授权
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userParam, user);
        List<String> orgMgrIds = user.getOrgMgrIds();
        List<String> stationGroupIds = user.getStationGroupIds();
        List<String> functionIds = user.getFunctionIds();
        airStep03(orgMgrIds, stationGroupIds, functionIds, createId, userId, roleIds);
    }

    /**
     * 删除以前授权
     *
     * @param userId
     */
    private void deleteAirAuthByUserId(String userId, String roleId,
                                       List<String> mgrList,
                                       List<String> mgrStationGroup,
                                       List<String> userAuthFunctions) {
        //update:由于大小权限的问题导致这里不能全部删除以前授权的所有 2019-01-24
        //企业管理员，授权客户管理权限
        if (!CollectionUtils.isEmpty(mgrList)) {
            //删除以前的授权
            QueryWrapper<SysUserOrgMgr> orgMgr = new QueryWrapper<>();
            orgMgr.eq("user_id", userId);
            orgMgr.eq("role_id", roleId);
            orgMgr.in("org_id", mgrList);
            sysUserOrgMgrMapper.delete(orgMgr);
        }

        //企业设备管理员，授权设备管理权限
        if (!CollectionUtils.isEmpty(mgrStationGroup)) {
            //之前是企业设备管理员
            QueryWrapper<SysUserStationgroupMgrstation> station2 = new QueryWrapper<>();
            station2.eq("user_id", userId);
            station2.in("group_id", mgrStationGroup);
            userStationgroupMgrstationMapper.delete(station2);
        }

        //查询用户能使用的功能
        if (!CollectionUtils.isEmpty(userAuthFunctions)) {
            QueryWrapper<SysUserFunction> function = new QueryWrapper<>();
            function.eq("user_id", userId);
            function.eq("role_id", roleId);
            function.in("function_Id", userAuthFunctions);
            sysUserFunctionMapper.delete(function);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importUser(MultipartFile excelFile, String userId, Boolean isAdmin) {
        // 用户名验证规则
        String regEx = "^[a-zA-Z_][a-zA-Z0-9_]{0,}$";
        Pattern pattern = Pattern.compile(regEx);
        //邮箱校验规则
        String emailReg = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        Pattern emailPattern = Pattern.compile(emailReg);
        //手机号正则
        String phoneReg = "^((1\\d{2})+\\d{8})$";
        Pattern phonePattern = Pattern.compile(phoneReg);

        List<String> haveUserNameList = new ArrayList<>();
        List<String> haveMobilenoList = new ArrayList<>();

        AjaxResult result = new AjaxResult(WamingConstant.PART_SUCCESS, "", "");
        try (InputStream inputStream = excelFile.getInputStream()) {
            if (!(FileMagic.valueOf(inputStream) == FileMagic.OOXML)) {
                result.setErroMsg("请上传excel xlsx类型文件，建议使用官方提供的模板");
                return result;
            }
            //加载客户字典，只加载健康空气客户的
            List<SysOrg> orgList = sysOrgMapper.selectByMap(ImmutableMap.of("delete_flag", 0, "business_type", 2));
            Map<String, String> orgMap = new HashMap<>(orgList.size());
            orgList.forEach(it -> orgMap.put(it.getName(), it.getId()));

            //加载身份字典
            List<SysRole> roleDTOList = sysRoleMapper.selectByMap(ImmutableMap.of("delete_flag", 0));
            Map<String, String> roleMap = new HashMap<>(roleDTOList.size());
            roleDTOList.forEach(it -> roleMap.put(it.getName(), it.getId().toString()));

            //解析excel
            XSSFWorkbook workbook2007 = new XSSFWorkbook(excelFile.getInputStream());
            // 取得第一个sheet
            XSSFSheet sheet = workbook2007.getSheetAt(0);
            // 多少行
            int count = sheet.getLastRowNum();
            if (count < 1) {
                result.setErroMsg("Excel文件内容是空的");
                return result;
            }
            XSSFCell cell;
            String temp;
            List<SysUser> userList = new ArrayList<>();
            for (int i = 1; i <= count; i++) {
                // 获取行对象
                XSSFRow row = sheet.getRow(i);
                if (row == null) {// 如果为空，不处理
                    continue;
                }
                //登录名
                String userName = null;
                cell = row.getCell(0);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (!StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        userName = cell.getStringCellValue().trim();
                        Matcher matcher = pattern.matcher(userName);
                        if (!matcher.matches() || userName.length() < 2 || userName.length() > 20) {
                            result.setErroMsg("第" + i + "行登录名不合法,登录名不能以数字开头且只能包含字母，数字和下划线且长度不能小于2位且不大于20位!");
                            return result;
                        }
                        if (haveUserNameList.contains(userName) || userNameExist(userName)) {
                            result.setErroMsg("第" + i + "行登录名已经存在");
                            return result;
                        }
                        haveUserNameList.add(userName);
                    }
                }
                //姓名
                String fullName;
                cell = row.getCell(1);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (!StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        cell.setCellType(CellType.STRING);
                        fullName = cell.getStringCellValue().trim();
                        if (fullName.length() > 30) {
                            result.setErroMsg("第" + i + "行姓名超过30个字符");
                            return result;
                        }
                    } else {
                        result.setErroMsg("第" + i + "行姓名为空");
                        return result;
                    }
                } else {
                    result.setErroMsg("第" + i + "行姓名为空");
                    return result;
                }

                //性别
                Integer gender = null;
                cell = row.getCell(2);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    temp = cell.getStringCellValue().trim();
                    if ("男".equals(temp)) {
                        gender = 1;
                    } else {
                        gender = 2;
                    }
//                    if (!StringUtils.isEmpty(cell.getStringCellValue())) {
//                        temp = cell.getStringCellValue();
//                        if ("男".equals(temp)) {
//                            gender = 1;
//                        } else {
//                            gender = 2;
//                        }
//                    } else {
//                        result.setErroMsg("第" + i + "行性别为空");
//                        return result;
//                    }
                }
//                else {
//                    result.setErroMsg("第" + i + "行性别为空");
//                    return result;
//                }
                //手机号
                String mobileno = null;
                cell = row.getCell(3);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (!StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        mobileno = cell.getStringCellValue().trim();
                        if (!phonePattern.matcher(mobileno).matches()) {
                            result.setErroMsg("第" + i + "行手机号格式不正确");
                            return result;
                        }
                        if (haveMobilenoList.contains(mobileno) || mobilenoExist(mobileno)) {
                            result.setErroMsg("第" + i + "行手机号已经存在");
                            return result;
                        }
                        haveMobilenoList.add(mobileno);
                    } else {
                        if (StringUtils.isEmpty(userName)) {
                            result.setErroMsg("第" + i + "行登录名和手机号二者至少必填一项");
                            return result;
                        }
                    }
                } else {
                    if (StringUtils.isEmpty(userName)) {
                        result.setErroMsg("第" + i + "行登录名和手机号二者至少必填一项");
                        return result;
                    }
                }
                //邮箱
                String email = "";
                cell = row.getCell(4);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    email = cell.getStringCellValue().trim();
                    if (!StringUtils.isEmpty(email)) {
                        if (!emailPattern.matcher(email).matches()) {
                            result.setErroMsg("第" + i + "行邮箱格式不正确");
                            return result;
                        }
                    }
                    //else {
//                        result.setErroMsg("第" + i + "行邮箱为空");
//                        return result;
//                    }
                }
//                else {
//                    result.setErroMsg("第" + i + "行邮箱为空");
//                    return result;
//                }
                //地址
                cell = row.getCell(5);
                String workAddress = null;
                if (!StringUtils.isEmpty(cell)) {
                    workAddress = cell.getStringCellValue().trim();
                }

                //完全管理员
                SysUser sysUser = sysUserMapper.selectById(userId);
                Integer adminFlag = sysUser.getAdminFlag();


                //客户
                String orgId;
                cell = row.getCell(6);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (!StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        orgId = orgMap.get(cell.getStringCellValue().trim());
                        if (StringUtils.isEmpty(orgId)) {
                            result.setErroMsg("第" + i + "行" + "系统没有找到" + cell.getStringCellValue().trim() + "的健康空气客户");
                            return result;
                        } else {
                            //检验
                            if (!isAdmin && adminFlag != 1) {
                                //登录用户可管理的客户
                                List<SysOrg> sysUserOrgMgrs = sysUserOrgMgrMapper.findAllOrgAndChildByUser(userId, null)
                                        .stream().filter(it -> WamingConstant.ONE.equals(it.getManage())).collect(Collectors.toList());
                                List<String> loginMgr = new ArrayList<>();
                                sysUserOrgMgrs.forEach(e -> loginMgr.add(e.getId()));
                                if (!loginMgr.contains(orgId)) {
                                    result.setErroMsg("第" + i + "行" + "你没有" + cell.getStringCellValue().trim() + "客户的管理权限");
                                    return result;
                                }
                            }
                        }
                    } else {
                        result.setErroMsg("第" + i + "行客户为空");
                        return result;
                    }
                } else {
                    result.setErroMsg("第" + i + "行客户为空");
                    return result;
                }

                //用户身份
                String roleId;
                cell = row.getCell(7);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (!StringUtils.isEmpty(cell.getStringCellValue())) {
                        String roleName = cell.getStringCellValue();
                        roleId = roleMap.get(roleName.trim());
                        if (StringUtils.isEmpty(roleId)) {
                            result.setErroMsg("第" + i + "行" + "系统没有找到" + cell.getStringCellValue().trim() + "的用户身份");
                            return result;
                        }
                    } else {
                        result.setErroMsg("第" + i + "行用户身份为空");
                        return result;
                    }
                } else {
                    result.setErroMsg("第" + i + "行用户身份为空");
                    return result;
                }
                //用户组（可多个逗号分隔）
                //根据所属客户查询下面的用户组
                List<SysUsergroupDTO> userGroupList = usergroupMapper.getUserGroupList(orgId, "");
                Map<String, String> groupMap = new HashMap<>(roleDTOList.size());
                userGroupList.forEach(it -> groupMap.put(it.getName(), it.getId()));
                cell = row.getCell(8);
                List<String> groupIdList = new ArrayList<>();
                if (cell != null && !StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                    cell.setCellType(CellType.STRING);
                    String group = cell.getStringCellValue().trim();
                    String[] groupTemp = group.split(",");
                    for (String r : groupTemp) {
                        String groupId = groupMap.get(r);
                        if (StringUtils.isEmpty(groupId)) {
                            result.setErroMsg("第" + i + "行" + "系统没有找到" + r + "的用户组");
                            return result;
                        } else {
                            groupIdList.add(groupId);
                        }
                    }
                    if (groupTemp.length > groupIdList.size()) {
                        result.setErroMsg("用户组中包含没有权限的用户组");
                        return result;
                    }
                }
                List<String> stationGroupIdList = new ArrayList<>();
                List<String> orgIdList = new ArrayList<>();

                QueryWrapper<SysOrg> orgQuery = new QueryWrapper<>();
                orgQuery.eq("id", orgId);
                orgQuery.eq("delete_flag", "0");
                SysOrg sysOrg = sysOrgMapper.selectOne(orgQuery);

                if (UserRoleEnum.COMPANY_MANAGER_ID.code.equals(roleId)) {
                    //企业管理员的可管理客户或分支机构（可多个逗号分隔）
                    //查询有管理权限的客户
                    List<SysOrg> allManageOrgByUser = new ArrayList<>();
                    //登录用户为空
                    //if (isAdmin || adminFlag == 1) {
                    //    //查询全部
                    //    QueryWrapper<SysOrg> orgQuery = new QueryWrapper<>();
                    //    orgQuery.eq("delete_flag", "0");
                    //    orgQuery.eq("business_type", 2);
                    //    allManageOrgByUser = sysOrgMapper.selectList(orgQuery);
                    //} else {
                    //allManageOrgByUser = sysUserOrgMgrMapper.findAllManageOrgByUser(userId, "2");
                    //allManageOrgByUser = allManageOrgByUser.stream().filter(sysOrg -> sysOrg.getManage() == 1).collect(Collectors.toList());
                    //}
                    Map<String, String> orgMgrMap = new HashMap<>(roleDTOList.size());
                    /*update(2019-01-23):去掉校验 必须是所属客户下的客户*/
                    String parentId;
                    if (sysOrg.getCategory() == 1) {
                        allManageOrgByUser.add(sysOrg);
                        //一级客户,查询下面的子客户
                        parentId = sysOrg.getId();
                        allManageOrgByUser = sysOrgMapper.selectByMap(ImmutableMap.of("parent_id", parentId, "delete_flag", 0));
                        allManageOrgByUser.add(sysOrg);
                    } else {
                        parentId = sysOrg.getParentId();
                        SysOrg parent = sysOrgMapper.selectById(parentId);
                        allManageOrgByUser = sysOrgMapper.selectByMap(ImmutableMap.of("parent_id", parentId, "delete_flag", 0));
                        allManageOrgByUser.add(parent);
                    }
                    /*end*/

                    allManageOrgByUser.forEach(it -> orgMgrMap.put(it.getName(), it.getId()));
                    cell = row.getCell(9);
                    if (cell != null && !StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        cell.setCellType(CellType.STRING);
                        String org = cell.getStringCellValue().trim();
                        String[] orgTemp = org.split("[,|，]");
                        for (String r : orgTemp) {
                            String groupId = orgMgrMap.get(r);
                            if (StringUtils.isEmpty(groupId)) {
                                result.setErroMsg("第" + i + "行" + "可管理客户有误\"" + r + "\"");
                                return result;
                            } else {
                                orgIdList.add(groupId);
                            }
                        }
                        //if (orgTemp.length > orgIdList.size()) {
                        //    result.setErroMsg("用户组中包含没有权限的客户");
                        //    return result;
                        //}
                    }
                } else if (UserRoleEnum.COMPANY_EQUIPMENT_MANAGER_ID.code.equals(roleId) ||
                        UserRoleEnum.COMPANY_USER_ID.code.equals(roleId)) {
                    List<SysStationGroup> sysStationGroupList;
                    //企业设备管理员的可管理设备组（可多个逗号分隔）
                    /*update(2019-01-23):去掉校验 必须是所属客户下的客户的设备组*/
                    List<String> orgIgs = new ArrayList<>();
                    if (sysOrg != null && sysOrg.getCategory() == 1) {
                        //一级客户，查询下面的子节点
                        List<SysOrg> sysOrgs = sysOrgMapper.selectByMap(ImmutableMap.of("parent_id", sysOrg.getId(), "delete_flag", 0));
                        sysOrgs.forEach(e -> orgIgs.add(e.getId()));
                        orgIgs.add(sysOrg.getId());
                    } else {
                        //查询上级客户
                        String parentId = sysOrg.getParentId();
                        //上级客户所有的分支结构
                        List<SysOrg> sysOrgs = sysOrgMapper.selectByMap(ImmutableMap.of("parent_id", parentId, "delete_flag", 0));
                        sysOrgs.forEach(e -> orgIgs.add(e.getId()));
                        orgIgs.add(parentId);
                    }
                    //一级客户以及子客户的设备组
                    QueryWrapper<SysStationGroup> groupQuery = new QueryWrapper<>();
                    groupQuery.in("org_id", orgIgs);
                    groupQuery.eq("delete_flag", 0);
                    sysStationGroupList = sysStationGroupMapper.selectList(groupQuery);
                    /*end*/
                    //if (sysOrg != null && sysOrg.getCategory() == 1) {
                    //    //一级客户，查询下面的子节点
                    //    QueryWrapper<SysOrg> subQuery = new QueryWrapper<>();
                    //    subQuery.eq("parent_id", sysOrg.getId());
                    //    subQuery.eq("delete_flag", 0);
                    //    List<SysOrg> sysOrgs = sysOrgMapper.selectList(subQuery);
                    //    List<String> orgIgs = new ArrayList<>();
                    //    sysOrgs.forEach(e -> orgIgs.add(e.getId()));
                    //    orgIgs.add(sysOrg.getId());
                    //    //一级客户以及子客户的设备组
                    //    QueryWrapper<SysStationGroup> groupQuery = new QueryWrapper<>();
                    //    groupQuery.in("org_id", orgIgs);
                    //    groupQuery.eq("delete_flag", 0);
                    //    sysStationGroupList = sysStationGroupMapper.selectList(groupQuery);
                    //} else {
                    //    //分支机构
                    //    //本组织的设备组
                    //    QueryWrapper<SysStationGroup> groupQuery = new QueryWrapper<>();
                    //    groupQuery.in("org_id", sysOrg.getId());
                    //    groupQuery.eq("delete_flag", 0);
                    //    List<SysStationGroup> sysStationGroups = sysStationGroupMapper.selectList(groupQuery);
                    //    //本组织可用设备组
                    //    QueryWrapper<SysOrgStationGroup> orgQuery2 = new QueryWrapper<>();
                    //    orgQuery2.in("org_id", sysOrg.getId());
                    //    List<SysOrgStationGroup> sysOrgStationGroups = sysOrgStationGroupMapper.selectList(orgQuery2);
                    //    List<String> groupIds = new ArrayList<>();
                    //    sysOrgStationGroups.forEach(e -> groupIds.add(e.getGroupId()));
                    //    QueryWrapper<SysStationGroup> groupQuery2 = new QueryWrapper<>();
                    //    groupQuery2.in("id", groupIds);
                    //    groupQuery2.eq("delete_flag", 0);
                    //    List<SysStationGroup> sysStationGroups1 = sysStationGroupMapper.selectList(groupQuery2);
                    //    sysStationGroups.addAll(sysStationGroups1);
                    //    sysStationGroupList.addAll(sysStationGroups);
                    //}
                    Map<String, String> stationGroupMap = new HashMap<>(roleDTOList.size());
                    sysStationGroupList.forEach(it -> stationGroupMap.put(it.getName(), it.getId()));
                    cell = row.getCell(10);
                    if (cell != null && !StringUtils.isEmpty(cell.getStringCellValue().trim())) {
                        cell.setCellType(CellType.STRING);
                        String stationGroup = cell.getStringCellValue().trim();
                        String[] stationGroupTemp = stationGroup.split("[,|，]");
                        if (stationGroupTemp != null && stationGroupTemp.length > 0 && CollectionUtils.isEmpty(stationGroupMap)) {
                            result.setErroMsg("所属客户中没有设备组");
                            return result;
                        }
                        for (String r : stationGroupTemp) {
                            String groupId = stationGroupMap.get(r);
                            if (StringUtils.isEmpty(groupId)) {
                                result.setErroMsg("第" + i + "行" + "设备组有误\"" + r + "\"");
                                return result;
                            } else {
                                stationGroupIdList.add(groupId);
                            }
                        }
                        //if (stationGroupTemp.length > stationGroupIdList.size()) {
                        //    result.setErroMsg("用户组中包含没有权限的设备组");
                        //    return result;
                        //}
                    }
                }
                //添加用户基础信息
                SysUser user = new SysUser();
                String newUserId = UUID.randomUUID().toString().replaceAll("-", "");
                user.setId(newUserId);
                user.setUserType(1);
                user.setUserName(userName);
                user.setFullName(fullName);
                user.setFullNamePinyin(PinYinUtil.cn2Spell(fullName));
                user.setGender(gender);
                //使用默认密码
                QueryWrapper<SysCommonConfig> query = new QueryWrapper<>();
                query.eq("`key`", "user_default_pwd");
                SysCommonConfig sysCommonConfig = commonConfigMapper.selectOne(query);
                String defaultPwd = StringUtils.isEmpty(sysCommonConfig.getValue()) ? WamingConstant.DEFAULT_PWD : sysCommonConfig.getValue();
                user.setUserPassword(passwordEncoder.md5PasswordEncoder().encodePassword(defaultPwd, newUserId));
                user.setWorkEmail(email);
                user.setMobileno(mobileno);
                user.setWorkAddress(workAddress);
                user.setLoginCount(0);
                user.setDeleteFlag("0");
                user.setStatus("0");
                user.setCreateBy(userId);
                user.setCreateDt(new Date());
                user.setModifyBy(userId);
                user.setModifyDt(new Date());
                user.setRoleIds(Arrays.asList(roleId));
                user.setUserGroupIds(groupIdList);
                user.setOrgMgrIds(orgIdList);
                user.setOrgId(orgId);
                user.setStationGroupIds(stationGroupIdList);
                userList.add(user);
            }
            userList.forEach(user -> {
                String newUserId = user.getId();
                String userName = user.getUserName();
                if (!StringUtils.isEmpty(userName)) {
                    user.setIsDefault(0);
                } else {
                    user.setUserName(defaultUserName());
                    user.setIsDefault(1);
                }
                sysUserMapper.insert(user);
                //所属客户
                SysUserOrg userOrg = new SysUserOrg();
                userOrg.setOrgId(user.getOrgId());
                userOrg.setUserId(newUserId);
                userOrg.setCreateBy(userId);
                userOrg.setCreateDt(new Date());
                userOrg.setModifyBy(userId);
                userOrg.setModifyDt(new Date());
                sysUserOrgMapper.insert(userOrg);
                //用户身份
                insertUerRole(user.getRoleIds(), userId, newUserId);
                //添加用户组
                airStep02(user.getUserGroupIds(), userId, newUserId);
                //添加客户管理
                //添加设备组管理
                List<String> stationGroupIds = user.getStationGroupIds();
                airStep03(user.getOrgMgrIds(), stationGroupIds, null, userId, newUserId, user.getRoleIds());
                //检测数据授权
                String roleId = user.getRoleIds().get(0);
                if (UserRoleEnum.COMPANY_USER_ID.code.equals(roleId)) {
                    //企业管理员
                    if (!CollectionUtils.isEmpty(stationGroupIds)) {
                        stationGroupIds.forEach(stationGroupId -> {
                            SysUserStationGroup userStationGroup = new SysUserStationGroup();
                            userStationGroup.setUserId(newUserId);
                            userStationGroup.setGroupId(stationGroupId);
                            userStationGroup.setCreateBy(userId);
                            userStationGroup.setModifyBy(userId);
                            sysUserStationGroupMapper.insert(userStationGroup);
                        });
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            result.setErroMsg("出现未知错误");
            return result;
        }
        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    /**
     * 判断用户名是否在数据库中已经存在
     *
     * @param userName
     * @return
     */
    @Override
    public Boolean userNameExist(String userName) {
        QueryWrapper<SysUser> userParam = new QueryWrapper<>();
        userParam.eq("user_name", userName);
        userParam.eq("delete_flag", 0);
        Long count = this.baseMapper.selectCount(userParam);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean mobilenoExist(String mobileno) {
        QueryWrapper<SysUser> userParam = new QueryWrapper<>();
        userParam.eq("mobileno", mobileno);
        userParam.eq("delete_flag", 0);
        Long count = this.baseMapper.selectCount(userParam);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean emailExist(String email) {
        QueryWrapper<SysUser> userParam = new QueryWrapper<>();
        userParam.eq("work_email", email);
        userParam.eq("delete_flag", 0);
        Long count = this.baseMapper.selectCount(userParam);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser2UserGroup(UserBO userBO, String createId) {
        List<String> userGroupIds = userBO.getUserGroupIds();
        if (!CollectionUtils.isEmpty(userGroupIds)) {
            //删除以前的用户和用户组的关系
            QueryWrapper<SysUsergroupUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userBO.getUserId());
            sysUsergroupUserMapper.delete(queryWrapper);
            //添加新的用户组
            List<SysUsergroupUser> usergroupUsers = new ArrayList<>();
            userGroupIds.forEach(id -> {
                SysUsergroupUser usergroupUser = new SysUsergroupUser();
                usergroupUser.setGroupId(id);
                usergroupUser.setUserId(userBO.getUserId());
                usergroupUser.setCreateBy(createId);
                usergroupUser.setCreateDt(new Date());
                usergroupUser.setModifyBy(createId);
                usergroupUser.setModifyDt(new Date());
                usergroupUsers.add(usergroupUser);
            });
            return sysUsergroupUserMapper.insertList(usergroupUsers);
        } else {
            //删除所有用户组
            List<SysUsergroupUser> ug = sysUsergroupUserMapper.selectByMap(ImmutableMap.of("user_id", userBO.getUserId()));
            if (CollUtil.isEmpty(ug)) {
                return 1;
            } else {
                return sysUsergroupUserMapper.deleteByMap(ImmutableMap.of("user_id", userBO.getUserId()));
            }
        }
    }

    @Override
    public List<SysUser> getUserByOrgId(String orgId) {
        List<SysUserOrg> orgUsers = sysUserOrgMapper.selectByMap(ImmutableMap.of("org_id", orgId));
        if (!CollectionUtils.isEmpty(orgUsers)) {
            List<String> userIds = new ArrayList<>();
            orgUsers.forEach(userOrg -> userIds.add(userOrg.getUserId()));
            QueryWrapper<SysUser> userQuery = new QueryWrapper<>();
            userQuery.in("id", userIds);
            return sysUserMapper.selectList(userQuery);
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public JSONObject getAirUserAuth(String userId) {
        JSONObject result = new JSONObject();
        //判断用户身份
        List<UserRoleVO> roleByUserId = sysUserRoleMapper.findRoleByUserId(userId);
        Integer roleId = 0;
        if (!CollectionUtils.isEmpty(roleByUserId)) {
            UserRoleVO userRoleVO = roleByUserId.get(0);
            roleId = userRoleVO.getId();
        }
        //企业设备管理员
        if (UserRoleEnum.COMPANY_EQUIPMENT_MANAGER_ID.code.equals(roleId)) {
            //设备管理权限
            List<SysStationGroupVO> stationGroup = getMgrstationStationgroup(userId);
            result.put("auth", stationGroup);
        } else if (UserRoleEnum.COMPANY_USER_ID.code.equals(roleId)) {
            //企业用户，监测数据权限
            List<SysStationGroupVO> stationGroup = getAuthedStationGroup(userId);
            result.put("auth", stationGroup);
        } else {
            //企业管理员，获取授权的客户
            QueryWrapper<SysUserOrgMgr> orgMgrQuery = new QueryWrapper<>();
            orgMgrQuery.eq("user_id", userId);
            List<SysUserOrgMgr> sysUserOrgMgrs = sysUserOrgMgrMapper.selectList(orgMgrQuery);
            List<SysOrg> sysOrgs = Collections.EMPTY_LIST;
            if (!CollectionUtils.isEmpty(sysUserOrgMgrs)) {
                List<String> orgIds = new ArrayList<>();
                sysUserOrgMgrs.forEach(e -> orgIds.add(e.getOrgId()));
                QueryWrapper<SysOrg> orgQuery = new QueryWrapper<>();
                orgQuery.in("id", orgIds);
                sysOrgs = sysOrgMapper.selectList(orgQuery);
            }
            result.put("auth", sysOrgs);
        }
        //功能
        QueryWrapper<SysUserFunction> userFunQuery = new QueryWrapper<>();
        userFunQuery.eq("user_id", userId);
        List<SysUserFunction> sysUserFunctions = sysUserFunctionMapper.selectList(userFunQuery);
        List<String> funIds = new ArrayList<>();
        sysUserFunctions.forEach(e -> funIds.add(e.getFunctionId()));
        List<SysFunction> sysFunctions = Collections.EMPTY_LIST;
        if (!CollectionUtils.isEmpty(funIds)) {
            QueryWrapper<SysFunction> funQuery = new QueryWrapper<>();
            funQuery.in("id", funIds).and(w -> w.eq("delete_flag", 0)).and(w -> w.eq("menu_type", 2));
            sysFunctions = sysFunctionMapper.selectList(funQuery);
        }
        result.put("functions", sysFunctions);
        return result;
    }

    /**
     * 获取已经被授权监测数据权限的设备组
     *
     * @param userId
     * @return
     */
    private List<SysStationGroupVO> getAuthedStationGroup(String userId) {
        List<SysStationGroupVO> result = new ArrayList<>();
        //查询用户所在用户组
        QueryWrapper<SysUsergroupUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<SysUsergroupUser> usergroupUsers = sysUsergroupUserMapper.selectList(queryWrapper);
        List<String> usergroupIds = new ArrayList<>();
        usergroupUsers.forEach(e -> usergroupIds.add(e.getGroupId()));
        if (!CollectionUtils.isEmpty(usergroupIds)) {
            //用户组对应的设备组
            QueryWrapper<SysUserGroupStationGroup> sugsg = new QueryWrapper<>();
            sugsg.in("usergroup_id", usergroupIds);
            List<SysUserGroupStationGroup> sysUserGroupStationGroups = sysUsergroupStationgroupMapper.selectList(sugsg);
            List<String> stationGroupIds = new ArrayList<>();
            sysUserGroupStationGroups.forEach(e -> stationGroupIds.add(e.getStationGroupId()));
            if (!CollectionUtils.isEmpty(stationGroupIds)) {
                QueryWrapper<SysStationGroup> ssg = new QueryWrapper<>();
                ssg.in("id", stationGroupIds);
                List<SysStationGroup> sysStationGroups = sysStationGroupMapper.selectList(ssg);
                //来自用户组的授权，不能删除
                sysStationGroups.forEach(sg -> {
                    SysStationGroupVO temp = new SysStationGroupVO();
                    temp.setId(sg.getId().concat("_group"));
                    temp.setName(sg.getName());
                    temp.setFromUserGroup(1);
                    result.add(temp);
                });
            }
        }
        //设备管理授权的
        QueryWrapper<SysUserStationGroup> susg = new QueryWrapper<>();
        susg.eq("user_id", userId);
        List<SysUserStationGroup> sysUserStationGroups = sysUserStationGroupMapper.selectList(susg);
        List<String> groupIds = new ArrayList<>();
        sysUserStationGroups.forEach(e -> groupIds.add(e.getGroupId()));
        if (!CollectionUtils.isEmpty(groupIds)) {
            QueryWrapper<SysStationGroup> ssg2 = new QueryWrapper<>();
            ssg2.in("id", groupIds);
            List<SysStationGroup> sysStationGroups2 = sysStationGroupMapper.selectList(ssg2);
            //其他授权
            sysStationGroups2.forEach(sg -> {
                SysStationGroupVO temp = new SysStationGroupVO();
                temp.setId(sg.getId());
                temp.setName(sg.getName());
                temp.setFromUserGroup(0);
                result.add(temp);
            });
        }

        return result;
    }

    /**
     * 获取已经被授权设备管理权限的设备组
     *
     * @param userId
     * @return
     */
    private List<SysStationGroupVO> getMgrstationStationgroup(String userId) {
        List<SysStationGroupVO> result = new ArrayList<>();
        //查询用户已经分配的设备组
        List<String> mgrStationgroupIdList = userStationgroupMgrstationMapper.selectByMap(ImmutableMap.of("user_id", userId))
                .stream().map(SysUserStationgroupMgrstation::getGroupId).collect(Collectors.toList());
        if (mgrStationgroupIdList.isEmpty()) {
            //没有分配直接返回
            return result;
        }
        //根据设备组ID查询出所有设备组
        QueryWrapper<SysStationGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", mgrStationgroupIdList);
        return sysStationGroupMapper.selectList(queryWrapper).stream().map(it -> {
            SysStationGroupVO vo = new SysStationGroupVO();
            vo.setId(it.getId());
            vo.setName(it.getName());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 保存时逐一校验，设备组的所属组织是此用户的所属组织的上级时（也就是上级的设备组由下级用户组可以查看数据），
     * 判断此用户组的所属组织此前是否已被授权使用此设备组。如果没有授权时，提示确认信息，确认保存后，为此用户组的所属组织赋予使用此设备组的权限。
     *
     * @param stationGroupBO
     * @return
     */
    @Override
    public List<SysOrgStationGroup> checkStaionGroupAuth(StationGroupBO stationGroupBO) {
        //查询设备组所属组织
        QueryWrapper<SysStationGroup> stationGroupQuery = new QueryWrapper<>();
        stationGroupQuery.in("id", stationGroupBO.getStationGroupIds());
        List<SysStationGroup> sysStationGroups = sysStationGroupMapper.selectList(stationGroupQuery);
        //查询客户所属组织详情
        SysOrg sysOrg = sysOrgMapper.selectById(stationGroupBO.getOrgId());
        String parentId = sysOrg.getParentId();
        List<SysOrgStationGroup> result = new ArrayList<>();
        if (!StringUtils.isEmpty(parentId)) {
            sysStationGroups.forEach(stationGroup -> {
                String orgId2 = stationGroup.getOrgId();
                if (orgId2.equals(parentId)) {
                    //设备组的所属组织是此用户的所属组织的上级时
                    QueryWrapper<SysOrgStationGroup> orgstationGroupQuery = new QueryWrapper<>();
                    orgstationGroupQuery.eq("org_id", orgId2).and(w -> w.eq("group_id", stationGroup.getId()));
                    List<SysOrgStationGroup> sysOrgStationGroups = sysOrgStationGroupMapper.selectList(orgstationGroupQuery);
                    result.addAll(sysOrgStationGroups);
                }
            });
        }
        return result;
    }

    @Override
    public Boolean hasAllAuth2LoginUser(String userId, boolean admin) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        int adminFlag = sysUser.getAdminFlag();
        if (admin || adminFlag == 1) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新登录状态
     * 0未激活 1登录中 2退出 3锁定 4禁用
     *
     * @param userId
     * @param status
     */
    @Override
    public void updateLoginStatus(String userId, String status) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setStatus(status);
        this.baseMapper.updateById(user);
    }

    @Override
    public void loguot(String userId) {
        SysUser sysUser = this.baseMapper.selectById(userId);
        if (Integer.parseInt(sysUser.getStatus()) > 2) {
            return;
        }
        SysUser user = new SysUser();
        user.setId(userId);
        user.setStatus("2");
        this.baseMapper.updateById(user);
    }

    @Override
    public Boolean isFullAdmin(String userId) {
        if (StrUtil.isBlank(userId)) {
            return false;
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        //完全管理权限这里等同于超级管理员
        if (sysUser != null && WamingConstant.ONE.equals(sysUser.getAdminFlag())) {
            return true;
        }
        return false;
    }

    @Override
    public UserRoles getAllRoles(String userId) {
        UserRoles ur = new UserRoles();
        List<MiniRole> roles = sysUserMapper.getAllRoles(userId);
        ur.setUserId(userId);
        ur.setRoles(roles);
        return ur;
    }

    /**
     * 根据用户ID获取用户角色
     *
     * @param updateUserId
     * @return
     */
    @Override
    public Integer getUserRole(String updateUserId) {
        List<UserRoleVO> roles = sysUserRoleMapper.findRoleByUserId(updateUserId);
        if (CollUtil.isNotEmpty(roles)) {
            return roles.get(0).getId();
        }
        return -1;
    }

    @Override
    public void deleteOrgMgr(String updateUserId, String roleId) {
        QueryWrapper<SysUserOrgMgr> orgMgr = new QueryWrapper<>();
        orgMgr.eq("user_id", updateUserId);
        orgMgr.eq("role_id", roleId);
        sysUserOrgMgrMapper.delete(orgMgr);
    }

    @Override
    public void deleteStationGroup(String updateUserId, String roleId) {
        QueryWrapper<SysUserStationgroupMgrstation> station2 = new QueryWrapper<>();
        station2.eq("user_id", updateUserId);
        station2.in("role_id", roleId);
        userStationgroupMgrstationMapper.delete(station2);
        QueryWrapper<SysUserStationGroup> userStationGroupQueryWrapper = new QueryWrapper<>();
        station2.eq("user_id", updateUserId);
        sysUserStationGroupMapper.delete(userStationGroupQueryWrapper);
    }

    /**
     * 功能描述: 登录接口
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2021/1/25 上午11:53
     */
    @SneakyThrows
    @Override
    public LoginUserDTO loginAllPlatforms(LoginRequest request) {

        //先查询用户
        SysUser sysUser = findByUserNameOrPhone(request.getUsername());
        if (Objects.isNull(sysUser)) {
            return new LoginUserDTO().setLoginSuccess(false).setFailMessage("未找到" + request.getUsername() + "用户");
        }
        //比对用户密码
        if ((!sysUser.getUserPassword().equals(md5PasswordEncoder.encodePassword(request.getPassword(), sysUser.getId())))
                && (!sysUser.getUserPassword().equals(md5PasswordEncoder.encodePassword(request.getPassword(), sysUser.getUserName())))) {
            return new LoginUserDTO().setLoginSuccess(false).setFailMessage("用户名或密码错误");
        }

        //超级管理员不检查权限
        if (!sysUser.getUserName().equals("admin")) {
            boolean isAuth = false;
            //查询用户所有的角色和业务种类
            List<UserRoleBo> roleBoList = sysUserRoleMapper.findRoleInfoByUserId(sysUser.getId());
            //对比业务种类
            for (UserRoleBo roleBo : roleBoList) {
                if (request.getBusinessType().equals(roleBo.getBusinessType())) {
                    isAuth = true;
                    break;
                }
            }
            //检查权限
            if (!isAuth) {
                return new LoginUserDTO().setLoginSuccess(false).setFailMessage("无权登录此平台");
            }
        }
        //登录更新用户最后登录时间和登录次数
        sysUserMapper.updateLoginInfo(sysUser.getUserName());

        //返回登陆信息
        final LoginUserDTO loginUserInfo = sysUserMapper.findLoginUserInfo(sysUser.getId());
        loginUserInfo.setLoginSuccess(true)
                .setIsAdmin(SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName()) ? 1 : 0);

        UserRoles allRoles = this.getAllRoles(sysUser.getId());
        allRoles.setAdminFlag(sysUser.getAdminFlag());
        allRoles.setIsAdmin(SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName()) ? 1 : 0);
        allRoles.setUserType(sysUser.getUserType());
        List<SysDomain> sysDomainList = sysDomainMapper.findByUserId(loginUserInfo.getUserId());
        // 生成token
        String token = JwtUtil.sign(sysUser.getUserName(), sysUser.getUserPassword());
        // 设置token缓存有效时间
        redisUtil.set(WamingConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(WamingConstant.PREFIX_USER_TOKEN + token, 36000);
        loginUserInfo.setToken(token);
        if (Integer.valueOf(1).equals(loginUserInfo.getCaptainFlag())) {
            //如果是网格长，也是网格员
            loginUserInfo.setGridFlag(1);
        }
        return loginUserInfo;


    }

    @Override
    public List<UserRoleBo> findRoleByUser(String userId) {
        List<UserRoleBo> roleBoList = sysUserRoleMapper.findRoleInfoByUserId(userId);
        return roleBoList;
    }

    /**
     * 查询用户身份信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserFlagDTO findUserFlag(String userId) {
        //返回登陆信息
        UserFlagDTO userFlagDTO = sysUserMapper.findUserFlag(userId);
        userFlagDTO.setIsAdmin(SecurityConstants.ADMIN_USER_NAME.equals(userFlagDTO.getUserName()) ? 1 : 0);
        if (Integer.valueOf(1).equals(userFlagDTO.getCaptainFlag())) {
            //如果是网格长，也是网格员
            userFlagDTO.setGridFlag(1);
        }
        return userFlagDTO;
    }

    /**
     * 保存网格化用户信息
     */
    @Transactional
    @Override
    public AjaxResult saveGridUserData(UserGridDataDTO dto) {
        SysUser entity = sysUserMapper.selectById(dto.getUserId());
        if (entity == null) {
            return AjaxResult.fail("用户不存在，请刷新重试");
        }
        entity.setTaskOrgId(dto.getTaskOrgId());
        entity.setDomainId(dto.getDomainId());
        sysUserMapper.updateById(entity);
        if (!CollectionUtils.isEmpty(dto.getTaskOrgIds())) {
            //溯源任务附加权限
            List<SysUserTaskOrg> taskOrgList = new ArrayList<>();
            dto.getTaskOrgIds().forEach(taskOrgId -> {
                SysUserTaskOrg taskOrg = new SysUserTaskOrg();
                taskOrg.setUserId(dto.getUserId());
                taskOrg.setOrgId(taskOrgId);
                taskOrgList.add(taskOrg);
            });
            //先删除，在批量新增
            sysUserTaskOrgMapper.delByUserId(dto.getUserId());
            //新增
            sysUserTaskOrgMapper.saveList(taskOrgList);
        } else {
            //清空
            sysUserTaskOrgMapper.delByUserId(dto.getUserId());
        }
        if (dto.getIdentity() != null) {
            //网格化附加身份
            SysUserInfo userInfo = new SysUserInfo();
            BeanUtils.copyProperties(dto.getIdentity(), userInfo);
            userInfo.setUserId(dto.getUserId());
            //先删除在新增
            sysUserMapper.delUserInfo(dto.getUserId());
            //新增
            sysUserMapper.saveUserInfo(userInfo);
        } else {
            //清空
            sysUserMapper.delUserInfo(dto.getUserId());
        }
        if (!CollectionUtils.isEmpty(dto.getDomainIds())) {
            //可用区域
            List<SysUserDomain> domainList = new ArrayList<>();
            dto.getDomainIds().forEach(e -> {
                SysUserDomain domain = new SysUserDomain();
                domain.setDomainId(Long.valueOf(e));
                domain.setUserId(dto.getUserId());
                domainList.add(domain);
            });
            //先清空在保存
            sysUserMapper.delUserDomain(dto.getUserId());
            //新增
            sysUserMapper.saveUserDomain(domainList);
        } else {
            //清空
            sysUserMapper.delUserDomain(dto.getUserId());
        }

        return AjaxResult.success();
    }

    /**
     * 查询 网格化用户信息数据
     */
    @Override
    public UserGridDataDTO selectGridUserData(String userId) {
        SysUser entity = sysUserMapper.selectById(userId);
        if (entity == null) {
            return null;
        }
        UserGridDataDTO vo = new UserGridDataDTO();
        vo.setUserId(userId);
        vo.setDomainId(entity.getDomainId());
        vo.setTaskOrgId(entity.getTaskOrgId());
        //溯源任务附加权限
        QueryWrapper<SysUserTaskOrg> taskOrgWrapper = new QueryWrapper<>();
        taskOrgWrapper.eq("user_id", userId);
        List<SysUserTaskOrg> taskOrgList = sysUserTaskOrgMapper.selectList(taskOrgWrapper);
        if (!CollectionUtils.isEmpty(taskOrgList)) {
            vo.setTaskOrgIds(new ArrayList<>());
            taskOrgList.forEach(task -> {
                vo.getTaskOrgIds().add(task.getOrgId());
            });
        }
        SysUserInfo userInfo = sysUserMapper.selectUserInfoByUserId(userId);
        if (userInfo != null) {
            //网格化附加身份
            UserGridDataDTO.IdentityData identityData = new UserGridDataDTO.IdentityData();
            BeanUtils.copyProperties(userInfo, identityData);
            vo.setIdentity(identityData);
            if (identityData.getCity() != null) {
                //查询省
                SysDomain sysDomain = sysDomainMapper.selectById(identityData.getCity());
                if (sysDomain != null) {
                    identityData.setProvince(sysDomain.getParentId().intValue());
                }
            }
        } else {
            vo.setIdentity(new UserGridDataDTO.IdentityData());
        }
        List<SysUserDomain> userDomainList = sysUserMapper.selectUserDomainByUserId(userId);
        if (!CollectionUtils.isEmpty(userDomainList)) {
            //可用区域
            vo.setDomainIds(new ArrayList<>());
            userDomainList.forEach(e -> {
                vo.getDomainIds().add(e.getDomainId().toString());
            });
        }
        return vo;
    }

    @Override
    public List<DomainTreeVO> selectUserDomainTree(String userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser == null) {
            return null;
        }
        //boolean isAdmin = WamingConstant.ADMIN_USER_NAME.equalsIgnoreCase(sysUser.getUserName()) || sysUser.getAdminFlag().intValue() == 1;
        List<SysUserDomain> userDomainList = sysUserMapper.selectUserDomainByUserId(userId);
        if (CollectionUtils.isEmpty(userDomainList)) {
            return null;
        }
        List<Long> domainIds = userDomainList.stream().map(SysUserDomain::getDomainId).collect(Collectors.toList());

        //查询区域
        List<DomainTreeVO> domainList = sysDomainService.selectTreeByIds(domainIds);
        return domainList;
    }

    @Override
    public List<UserDomainDTO> selectUserDomainList(String userId) {
        if (userId == null) {
            return null;
        }
        List<UserDomainDTO> voList = sysUserMapper.findUserDomains(userId);

//        List<SysUserDomain> userDomainList = sysUserMapper.selectUserDomainByUserId(userId);
//        if (CollectionUtils.isEmpty(userDomainList)) {
//            return null;
//        }
//        List<Long> domainIds = userDomainList.stream().map(SysUserDomain::getDomainId).collect(Collectors.toList());
//        List<SysDomain> domainList = sysDomainMapper.selectBatchIds(domainIds);
//        if (CollectionUtils.isEmpty(domainList)){
//            return null;
//        }
//        List<UserDomainDTO> voList = new ArrayList<>();
//        domainList.forEach(domain -> {
//            UserDomainDTO vo = new UserDomainDTO();
//            vo.setId(domain.getId());
//            vo.setParentId(domain.getParentId());
//            vo.setCityType(Integer.valueOf(domain.getCityType()));
//            vo.setDomainName(domain.getDomainName());
//            vo.setLatB(domain.getLatB() != null ? domain.getLatB().toString() : "");
//            vo.setLngB(domain.getLngB() != null ? domain.getLngB().toString() : "");
//            vo.setLatReal(domain.getLatReal() != null ? domain.getLatReal().toString() : "");
//            vo.setLngReal(domain.getLngReal() != null ? domain.getLngReal().toString() : "");
//            voList.add(vo);
//        });
        return voList;
    }

    @Override
    public LoginUserDTO getUserByUserId(String userId) {
        LoginUserDTO loginUserDTO = sysUserMapper.findLoginUserInfo(userId);
        if (loginUserDTO != null) {
            List<String> userOrgList = sysUserMapper.getUserOrg(loginUserDTO.getUserId());
            if (CollUtil.isNotEmpty(userOrgList)) {
                loginUserDTO.setOrgName(userOrgList.get(0));
            }
            if (StrUtil.isNotBlank(loginUserDTO.getAvatar())) {
                loginUserDTO.setAvatar(cosUrl + "/" + loginUserDTO.getAvatar());
            }
        }
        List<MiniRole> roles = sysUserMapper.getAllRoles(userId);
        if (roles != null && roles.size() > 0) {
            List<String> lists = new ArrayList<>();
            for (MiniRole role : roles) {
                if (Objects.nonNull(role)) {
                    lists.add(String.valueOf(role.getRoleId()));
                }
            }
            loginUserDTO.setRoles(lists);
        }
        return loginUserDTO;
    }


    /**
     * 按照登录名和姓名模糊查询所有用户
     *
     * @param name 模糊查询的名称
     * @return 用户列表
     */
    @Override
    public List<SimpleUserDTO> findUserLike(String name) {
        return sysUserMapper.findUserLike(name);
    }


    /**
     * @param name
     * @return
     */
    @Override
    public LoginUserDTO getUserByName(String name) {
        LoginUserDTO loginUserDTO = sysUserMapper.getUserByName(name);
        if (loginUserDTO == null) {
            return null;
        }
        List<MiniRole> roles = sysUserMapper.getAllRoles(loginUserDTO.getUserId());
        if (roles != null && roles.size() > 0) {
            List<String> lists = new ArrayList<>();
            for (MiniRole role : roles) {
                if (Objects.nonNull(role)) {
                    lists.add(String.valueOf(role.getRoleId()));
                }
            }
            loginUserDTO.setRoles(lists);
        }
        return loginUserDTO;
    }

    /**
     * 通过用户ID列表批量查询用户信息
     *
     * @param idList 用户ID列表
     * @return 用户信息列表
     */
    @Override
    public List<SimpleUserDTO> findByIdList(Collection<String> idList) {
        return sysUserMapper.findByIdList(idList);
    }

    /**
     * 通过用户ID列表批量查询用户信息
     *
     * @return 用户信息列表
     */
    @Override
    public List<SimpleUserDTO> findUsernameList(Collection<String> userNameList) {
        return sysUserMapper.findByUsernameList(userNameList);
    }

    /**
     * 查询客户下的用户
     */
    @Override
    public List<SimpleUserDTO> findByOrgId(String orgId) {
        return sysUserMapper.findSimpleInfoByOrgId(orgId);
    }

    /**
     * 查询网格员用户
     */
    @Override
    public List<GridUserDTO> findGridUser(GridUserParam param) {
        boolean isAdmin = false;
        //是否超管
        if (WamingConstant.ADMIN_USER_ID.equals(param.getUserId())) {
            isAdmin = true;
        }
        SysUser sysUser = sysUserMapper.selectById(param.getUserId());
        //登录用户为空
        if (sysUser == null) {
            return Collections.emptyList();
        }
        //完全管理权限
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }
        return sysUserMapper.findGridUser(param.getDomainId(), param.getOrgIds(), isAdmin);
    }

    /**
     * 查询用户分配的区域
     */
    @Override
    public List<UserDomainDTO> findUserDomain(String userId) {
        return sysUserMapper.findUserDomains(userId);
    }

    /**
     * 修改用户密码
     *
     * @param param
     * @return
     */
    @Override
    public AjaxResult changePassword(ChangePwdParam param) {
        AjaxResult ajaxResult = new AjaxResult();
        String userId = param.getUserId();
        SysUser user = sysUserMapper.selectById(userId);
        String pwd = user.getUserPassword();
        String oldMd5 = md5PasswordEncoder.encodePassword(param.getOldPwd(), user.getUserName());
        //新版密码加密方式
        String oldMd5New = md5PasswordEncoder.encodePassword(param.getOldPwd(), userId);

        if (!oldMd5.equals(pwd) && !oldMd5New.equals(pwd)) {
            ajaxResult.setErroCode(3000);
            ajaxResult.setErroMsg("您输入的原始密码不正确，请确认！");
        } else {
            sysUserMapper.updatePasswordById(userId, md5PasswordEncoder.encodePassword(param.getNewPwd(), userId));
            ajaxResult.setErroCode(2000);
            ajaxResult.setResult("密码修改成功");
        }
        return ajaxResult;
    }

    @Override
    public String resetSelfPassword(ChangePwdParam param) {
        String userId = param.getUserId();
        SysUser user = sysUserMapper.selectById(userId);
        String password = user.getUserPassword();
        if (password.contains("{bcrypt}")) {
            BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
            if (!bcryptPasswordEncoder.matches(param.getOldPwd(), password)) {
                throw new WmCommonException("旧密码不正确");
            }
        } else {
            if (!md5PasswordEncoder.isPasswordValid(password, param.getOldPwd(), userId)) {
                throw new WmCommonException("旧密码不正确");
            }
        }
        sysUserMapper.updatePasswordById(userId, md5PasswordEncoder.encodePassword(param.getNewPwd(), userId));
        return "success";
    }

    /**
     * 云平台注册用户
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public String register(CloudApiRequest.RegisterParam param, String orgId, String orderId) {
        //邮箱作为用户名
        List<SimpleUserDTO> userList = sysUserMapper.findByUsernameList(Collections.singletonList(param.getEmail()));
        if (CollUtil.isNotEmpty(userList)) {
            return userList.get(0).getId();
        }
        //检查手机号
        Long phoneCount = sysUserMapper.selectCount(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getMobileno, param.getPhone())
                .eq(SysUser::getDeleteFlag, 0));
        if (phoneCount > 0) {
            throw new WmCommonException("手机号已被其他用户使用");
        }
        int isOrgAdmin = 0;
        //注册时先检查组织下是否存在用户，如不存在，第一次注册的用户为该企业的企业管理员，每个企业暂定为一位企业管理员
        LambdaQueryWrapper<SysUserOrg> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUserOrg::getOrgId, orgId);
        Long count = sysUserOrgMapper.selectCount(wrapper);
        if (count <= 0) {
            isOrgAdmin = 1;
        }
        //保存用户信息
        SysUser sysUser = new SysUser();
        String id = UlidCreator.getMonotonicUlid().toString().toLowerCase();
        sysUser.setId(id)
                .setUserName(param.getEmail())
                .setUserPassword(passwordEncoder.md5PasswordEncoder().encodePassword(param.getPassword(), id))
                .setFullName(DesensitizedUtil.email(param.getEmail()))
                .setIsDefault(1)
                .setGender(1)
                .setWorkEmail(param.getEmail())
                .setMobileno(param.getPhone())
                .setStatus("0")
                .setAdminFlag(0)
                .setOrgAdmin(isOrgAdmin)
                .setUserType(4)
                .setCreateBy("register")
                .setCreateDt(new Date());
        sysUserMapper.insert(sysUser);

        //用户组织信息
        SysUserOrg sysUserOrg = new SysUserOrg();
        sysUserOrg.setUserId(id)
                .setCreateBy("cloud")
                .setCreateDt(new Date())
                .setOrgId(orgId);
        sysUserOrgMapper.insert(sysUserOrg);

        List<SysUserRole> roleList = new ArrayList<>();
        //企业管理员特殊处理
        if (isOrgAdmin == 1) {
            //可管理的组织
            SysUserOrgMgr sysUserOrgMgr = new SysUserOrgMgr();
            sysUserOrgMgr.setUserId(sysUser.getId())
                    .setOrgId(orgId)
                    .setRead(1)
                    .setManage(1)
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            sysUserOrgMgrMapper.insert(sysUserOrgMgr);

            //组织管理员赋予通用管理平台相应的角色
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId())
                    .setRoleId(374)  //通用平台-组织管理员
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            roleList.add(sysUserRole);

            SysUserRole admRole = new SysUserRole();//默认系统资源使用权限
            admRole.setUserId(sysUser.getId())
                    .setRoleId(376)         ////系统资源-系统管理(系统资源所有权限)
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            roleList.add(admRole);
            //企业管理员角色
            SysUserRole orgManageRole = new SysUserRole();
            orgManageRole.setUserId(sysUser.getId())
                    .setRoleId(UcRoleEnum.ORG_MANAGE.code)
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            roleList.add(orgManageRole);
        } else {
            //设计器角色
            SysUserRole ucRole = new SysUserRole();
            ucRole.setUserId(sysUser.getId())
                    .setRoleId(UcRoleEnum.ENG.code)  //工作台
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            roleList.add(ucRole);

            SysUserRole resRole = new SysUserRole();//默认系统资源使用权限
            resRole.setUserId(sysUser.getId())
                    .setRoleId(375)         ////系统资源-基础权限（资源管理员）
                    .setCreateBy("cloud")
                    .setCreateDt(new Date())
                    .setModifyBy("cloud")
                    .setModifyDt(new Date());
            roleList.add(resRole);
        }

        sysUserRoleMapper.batchInsert(roleList);

        //用户管理的订单
        SysUserOrderMgr userOrderMgr = new SysUserOrderMgr();
        userOrderMgr.setUserId(id)
                .setCreateBy("cloud")
                .setCreateDt(new Date())
                .setOrderId(orderId)
                .setManage(1)
                .setRead(1);
        sysUserOrderMgrMapper.insert(userOrderMgr);

        //分享key都有值，说明是邀请应用成员

        if (param.getRoleId() != null && param.getAppId() != null && StrUtil.isNotBlank(param.getGroupId())) {
            //如果是拥有者角色
            if (UcRoleEnum.OWNER.code.equals(param.getRoleId())) {
                //修改应用拥有者
                SysBusinessApp app = businessAppMapper.selectOne(Wrappers.<SysBusinessApp>lambdaQuery().eq(SysBusinessApp::getBizCode, String.valueOf(param.getAppId())));
                app.setOwner(id);
                businessAppMapper.updateById(app);
                //老拥有者角色去掉
                sysUsergroupUserMapper.delete(Wrappers.<SysUsergroupUser>lambdaQuery().eq(SysUsergroupUser::getRoleId, UcRoleEnum.OWNER.code)
                        .eq(SysUsergroupUser::getAppId, param.getAppId()));
            }
            SysUsergroupUser usergroupUser = new SysUsergroupUser();
            usergroupUser.setUserId(id);
            usergroupUser.setRoleId(param.getRoleId());
            usergroupUser.setGroupId(param.getGroupId());
            usergroupUser.setAppId(param.getAppId());
            usergroupUser.setCreateBy(id);
            sysUsergroupUserMapper.insert(usergroupUser);
        }
        return id;
    }

    /**
     * 云平台用户找回密码
     */
    @Override
    public String findPassword(String email, String password) {
        LoginUserDTO user = sysUserMapper.getUserByName(email);
        if (Objects.isNull(user)) {
            throw new WmCommonException(email + "还未注册");
        }
        String md5Pwd = md5PasswordEncoder.encodePassword(password, user.getUserId());
        sysUserMapper.updatePasswordById(user.getUserId(), md5Pwd);
        return user.getUserId();
    }

    @Override
    public void cloudModifyUser(String userId, String fullName, String phone) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (!StrUtil.equals(phone, sysUser.getMobileno())) {
            //修改了手机号，判断手机号是否被使用了
            Long count = sysUserMapper.selectCount(Wrappers.<SysUser>lambdaQuery()
                    .eq(SysUser::getMobileno, phone)
                    .eq(SysUser::getDeleteFlag, 0));
            if (count > 1) {
                throw new WmCommonException(phone + "已被使用");
            }
        }
        sysUser.setFullName(fullName);
        sysUser.setMobileno(phone);
        sysUserMapper.updateById(sysUser);
    }


    public boolean isAdmin(String userId) {
        boolean adminFlag = false;
//        com.qingcloud.base.remote.pojo.LoginUserDTO loginUserDTO = LoginUtils.getCurrentUser(true);//UserContextHolder.getUserInfo();
//        SysUser sysUser = null;
//        if (loginUserDTO != null) {
//            sysUser=new SysUser();
//            sysUser.setAdminFlag(loginUserDTO.getAdminFlag());
//            sysUser.setUserName(loginUserDTO.getUsername());
//            sysUser.setOrgAdmin(loginUserDTO.getOrgAdminFlag());
//        }else{
//            loginUserDTO = sysUserMapper.findLoginUserInfo(userId);
//        }
        LoginUserDTO loginUserDTO = sysUserMapper.findLoginUserInfo(userId);
        if (loginUserDTO != null) {
            if ((loginUserDTO.getAdminFlag() != null && loginUserDTO.getAdminFlag() == 1)
                    || loginUserDTO.getUsername().equals(SecurityConstants.ADMIN_USER_NAME)) {
                //||(loginUserDTO.getOrgAdminFlag() != null && loginUserDTO.getOrgAdminFlag()==1) 组织管理员
                adminFlag = true;
            }
        }
        return adminFlag;
    }

    public boolean isOrgAdmin(String userId) {
        boolean adminFlag = false;
        LoginUserDTO loginUserDTO = sysUserMapper.findLoginUserInfo(userId);
        if (loginUserDTO != null) {
            if ((loginUserDTO.getAdminFlag() != null && loginUserDTO.getAdminFlag() != 1)
                    && !loginUserDTO.getUsername().equals(SecurityConstants.ADMIN_USER_NAME)
                    && (loginUserDTO.getOrgAdminFlag() != null && loginUserDTO.getOrgAdminFlag() == 1)) {//组织管理员
                adminFlag = true;
            }
        }
        return adminFlag;
    }

    @Override
    public void updateLoginInfoById(String userId) {
        sysUserMapper.updateLoginInfoById(userId);
    }

    /**
     * 用户头像
     */
    @Override
    public void saveAvatar(UserAvatarBO bo) {
        if (StrUtil.isBlank(bo.getUserId())) {
            throw new WmCommonException("用户ID不能为空");
        }
        if (StrUtil.isNotBlank(bo.getAvatar())) {
            sysUserMapper.updateUserAvatar(bo.getUserId(), bo.getAvatar());
        }
    }

    /**
     * 查询用户团队信息
     */
    @Override
    public UserTeamBO findTeamInfo(String userId) {
        UserTeamBO teamBO = new UserTeamBO();
        LoginUserDTO loginUserDTO = sysUserMapper.findLoginUserInfo(userId);
        if (loginUserDTO != null) {
            teamBO.setUserId(loginUserDTO.getUserId());
            List<String> userOrgList = sysUserMapper.getUserOrg(loginUserDTO.getUserId());
            if (CollUtil.isNotEmpty(userOrgList)) {
                teamBO.setOrgName(userOrgList.get(0));
            }
            if (StrUtil.isNotBlank(loginUserDTO.getAvatar())) {
                teamBO.setAvatar(cosUrl + "/" + loginUserDTO.getAvatar());
            }
        }
        teamBO.setTeamNum(sysUsergroupUserMapper.countTeam(userId));
        return teamBO;
    }

}
